forked from vercel/next.js
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Examples] Move api-routes-apollo-server-and-client-auth to SSG (verc…
…el#13849) Related to vercel#11014 The authentication method has been replaced with an improved version of the passport example.
- Loading branch information
Showing
17 changed files
with
237 additions
and
271 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# Secrets like the one below should go into `.env.local` instead to avoid pushing | ||
# them to a repository, this is an exception for the sake of the example | ||
TOKEN_SECRET="this-is-a-secret-value-with-at-least-32-characters" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
169 changes: 33 additions & 136 deletions
169
examples/api-routes-apollo-server-and-client-auth/apollo/client.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,151 +1,48 @@ | ||
import Head from 'next/head' | ||
import { ApolloProvider } from '@apollo/react-hooks' | ||
import { useMemo } from 'react' | ||
import { ApolloClient } from 'apollo-client' | ||
import { InMemoryCache } from 'apollo-cache-inmemory' | ||
|
||
let globalApolloClient = null | ||
let apolloClient | ||
|
||
/** | ||
* Creates and provides the apolloContext | ||
* to a next.js PageTree. Use it by wrapping | ||
* your PageComponent via HOC pattern. | ||
* @param {Function|Class} PageComponent | ||
* @param {Object} [config] | ||
* @param {Boolean} [config.ssr=true] | ||
*/ | ||
export function withApollo(PageComponent, { ssr = true } = {}) { | ||
const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => { | ||
const client = apolloClient || initApolloClient(undefined, apolloState) | ||
return ( | ||
<ApolloProvider client={client}> | ||
<PageComponent {...pageProps} /> | ||
</ApolloProvider> | ||
) | ||
} | ||
|
||
// Set the correct displayName in development | ||
if (process.env.NODE_ENV !== 'production') { | ||
const displayName = | ||
PageComponent.displayName || PageComponent.name || 'Component' | ||
|
||
if (displayName === 'App') { | ||
console.warn('This withApollo HOC only works with PageComponents.') | ||
} | ||
|
||
WithApollo.displayName = `withApollo(${displayName})` | ||
} | ||
|
||
if (ssr || PageComponent.getInitialProps) { | ||
WithApollo.getInitialProps = async (ctx) => { | ||
const { AppTree } = ctx | ||
|
||
// Initialize ApolloClient, add it to the ctx object so | ||
// we can use it in `PageComponent.getInitialProp`. | ||
const apolloClient = (ctx.apolloClient = initApolloClient({ | ||
res: ctx.res, | ||
req: ctx.req, | ||
})) | ||
|
||
// Run wrapped getInitialProps methods | ||
let pageProps = {} | ||
if (PageComponent.getInitialProps) { | ||
pageProps = await PageComponent.getInitialProps(ctx) | ||
} | ||
|
||
// Only on the server: | ||
if (typeof window === 'undefined') { | ||
// When redirecting, the response is finished. | ||
// No point in continuing to render | ||
if (ctx.res && ctx.res.finished) { | ||
return pageProps | ||
} | ||
|
||
// Only if ssr is enabled | ||
if (ssr) { | ||
try { | ||
// Run all GraphQL queries | ||
const { getDataFromTree } = await import('@apollo/react-ssr') | ||
await getDataFromTree( | ||
<AppTree | ||
pageProps={{ | ||
...pageProps, | ||
apolloClient, | ||
}} | ||
/> | ||
) | ||
} catch (error) { | ||
// Prevent Apollo Client GraphQL errors from crashing SSR. | ||
// Handle them in components via the data.error prop: | ||
// https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error | ||
console.error('Error while running `getDataFromTree`', error) | ||
} | ||
|
||
// getDataFromTree does not call componentWillUnmount | ||
// head side effect therefore need to be cleared manually | ||
Head.rewind() | ||
} | ||
} | ||
|
||
// Extract query data from the Apollo store | ||
const apolloState = apolloClient.cache.extract() | ||
|
||
return { | ||
...pageProps, | ||
apolloState, | ||
} | ||
} | ||
} | ||
|
||
return WithApollo | ||
} | ||
|
||
/** | ||
* Always creates a new apollo client on the server | ||
* Creates or reuses apollo client in the browser. | ||
* @param {Object} initialState | ||
*/ | ||
function initApolloClient(ctx, initialState) { | ||
// Make sure to create a new client for every server-side request so that data | ||
// isn't shared between connections (which would be bad) | ||
if (typeof window === 'undefined') { | ||
return createApolloClient(ctx, initialState) | ||
} | ||
|
||
// Reuse client on the client-side | ||
if (!globalApolloClient) { | ||
globalApolloClient = createApolloClient(ctx, initialState) | ||
} | ||
|
||
return globalApolloClient | ||
} | ||
|
||
/** | ||
* Creates and configures the ApolloClient | ||
* @param {Object} [initialState={}] | ||
*/ | ||
function createApolloClient(ctx = {}, initialState = {}) { | ||
const ssrMode = typeof window === 'undefined' | ||
const cache = new InMemoryCache().restore(initialState) | ||
|
||
// Check out https://github.com/vercel/next.js/pull/4611 if you want to use the AWSAppSyncClient | ||
return new ApolloClient({ | ||
ssrMode, | ||
link: createIsomorphLink(ctx), | ||
cache, | ||
}) | ||
} | ||
|
||
function createIsomorphLink(ctx) { | ||
function createIsomorphLink() { | ||
if (typeof window === 'undefined') { | ||
const { SchemaLink } = require('apollo-link-schema') | ||
const { schema } = require('./schema') | ||
return new SchemaLink({ schema, context: ctx }) | ||
return new SchemaLink({ schema }) | ||
} else { | ||
const { HttpLink } = require('apollo-link-http') | ||
|
||
return new HttpLink({ | ||
uri: '/api/graphql', | ||
credentials: 'same-origin', | ||
}) | ||
} | ||
} | ||
|
||
function createApolloClient() { | ||
return new ApolloClient({ | ||
ssrMode: typeof window === 'undefined', | ||
link: createIsomorphLink(), | ||
cache: new InMemoryCache(), | ||
}) | ||
} | ||
|
||
export function initializeApollo(initialState = null) { | ||
const _apolloClient = apolloClient ?? createApolloClient() | ||
|
||
// If your page has Next.js data fetching methods that use Apollo Client, the initial state | ||
// get hydrated here | ||
if (initialState) { | ||
_apolloClient.cache.restore(initialState) | ||
} | ||
// For SSG and SSR always create a new Apollo Client | ||
if (typeof window === 'undefined') return _apolloClient | ||
// Create the Apollo Client once in the client | ||
if (!apolloClient) apolloClient = _apolloClient | ||
|
||
return _apolloClient | ||
} | ||
|
||
export function useApollo(initialState) { | ||
const store = useMemo(() => initializeApollo(initialState), [initialState]) | ||
return store | ||
} |
87 changes: 20 additions & 67 deletions
87
examples/api-routes-apollo-server-and-client-auth/apollo/resolvers.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ export const typeDefs = gql` | |
type User { | ||
id: ID! | ||
email: String! | ||
createdAt: Int! | ||
} | ||
input SignUpInput { | ||
|
20 changes: 8 additions & 12 deletions
20
examples/api-routes-apollo-server-and-client-auth/components/field.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.