Commit 62aa5c87 authored by Henrik Wenz's avatar Henrik Wenz Committed by Luis Alvarez D

Improve with-apollo-auth example (#8633)

* Remove connectToDevTools in favour of better default

* Remove redirect code from client

* Simplify function

* Remove apollo-boost

This package is optimized for client usage only.
We actually never used it. We only usered its reexports.

More info:
https://www.apollographql.com/docs/react/v2.5/recipes/authentication/#header

* Remove stopPropagation

We actually don’t need it.

* Refactor getToken method

We want to show how to get the token.
This can be from a cookie or some other isomorph store.
We are not interested in the cookie abstraction in this example.

* Secure cookie

not perfect but better than before….

* Add ssr config option

This was documented but not implemented
parent 5a9b0ba2
......@@ -47,7 +47,6 @@ const RegisterBox = () => {
<form
onSubmit={e => {
e.preventDefault()
e.stopPropagation()
create({
variables: {
......
......@@ -19,6 +19,8 @@ const SigninBox = () => {
const onCompleted = data => {
// Store the token in cookie
document.cookie = cookie.serialize('token', data.signinUser.token, {
sameSite: true,
path: '/',
maxAge: 30 * 24 * 60 * 60 // 30 days
})
// Force a reload of all the current queries now that the user is
......@@ -45,7 +47,6 @@ const SigninBox = () => {
<form
onSubmit={e => {
e.preventDefault()
e.stopPropagation()
signinUser({
variables: {
......
import React, { useMemo } from 'react'
import PropTypes from 'prop-types'
import cookie from 'cookie'
import { ApolloProvider } from '@apollo/react-hooks'
import Head from 'next/head'
import { ApolloClient, InMemoryCache, HttpLink } from 'apollo-boost'
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'
import { ApolloProvider } from '@apollo/react-hooks'
import fetch from 'isomorphic-unfetch'
/**
......@@ -15,7 +17,7 @@ import fetch from 'isomorphic-unfetch'
* @param {Object} [config]
* @param {Boolean} [config.ssr=true]
*/
export function withApollo (PageComponent) {
export function withApollo (PageComponent, { ssr = true } = {}) {
const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
const client = useMemo(() => {
// We pass in the apolloClient directly when using getDataFromTree
......@@ -24,11 +26,7 @@ export function withApollo (PageComponent) {
}
// Otherwise initClient using apolloState
return initApolloClient(apolloState, {
getToken: () => {
return parseCookies().token
}
})
return initApolloClient(apolloState, { getToken })
}, [])
return (
<ApolloProvider client={client}>
......@@ -59,59 +57,63 @@ export function withApollo (PageComponent) {
}
}
WithApollo.getInitialProps = async ctx => {
const { AppTree, req, res } = ctx
if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async ctx => {
const { AppTree } = ctx
// Run all GraphQL queries in the component tree
// and extract the resulting data
const apolloClient = (ctx.apolloClient = initApolloClient(
{},
{
getToken: () => parseCookies(req).token
}
))
const pageProps = PageComponent.getInitialProps
? await PageComponent.getInitialProps(ctx)
: {}
// Run all GraphQL queries in the component tree
// and extract the resulting data
const apolloClient = (ctx.apolloClient = initApolloClient(
{},
{
getToken: () => getToken(ctx.req)
}
))
const pageProps = PageComponent.getInitialProps
? 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 {}
}
if (res && res.finished) {
// When redirecting, the response is finished.
// No point in continuing to render
return {}
}
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)
}
}
// Get apolloState on the server (needed for ssr)
if (typeof window === 'undefined') {
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()
}
// 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()
// Extract query data from the Apollo store
const apolloState = apolloClient.cache.extract()
return {
...pageProps,
apolloState
return {
...pageProps,
apolloState
}
}
}
......@@ -164,7 +166,7 @@ function createApolloClient (initialState = {}, { getToken }) {
fetchOptions
})
const authLink = setContext((_, { headers }) => {
const authLink = setContext((request, { headers }) => {
const token = getToken()
return {
headers: {
......@@ -175,21 +177,18 @@ function createApolloClient (initialState = {}, { getToken }) {
})
// Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
const isBrowser = typeof window !== 'undefined'
return new ApolloClient({
connectToDevTools: isBrowser,
ssrMode: !isBrowser, // Disables forceFetch on the server (so queries are only run once)
ssrMode: typeof window === 'undefined', // Disables forceFetch on the server (so queries are only run once)
link: authLink.concat(httpLink),
cache: new InMemoryCache().restore(initialState)
})
}
/**
* Cookie parser that works on the
* server and on the client
* Get the user token from cookie
* @param {Object} req
* @param {Object} config
*/
function parseCookies (req, config = {}) {
return cookie.parse(req ? req.headers.cookie || '' : document.cookie, config)
function getToken (req) {
const cookies = cookie.parse(req ? req.headers.cookie || '' : document.cookie)
return cookies.token
}
......@@ -11,10 +11,13 @@
"dependencies": {
"@apollo/react-hooks": "^3.0.1",
"@apollo/react-ssr": "^3.0.1",
"apollo-boost": "^0.1.6",
"apollo-cache-inmemory": "1.6.3",
"apollo-client": "2.6.4",
"apollo-link-context": "^1.0.8",
"apollo-link-http": "1.5.15",
"cookie": "^0.3.1",
"graphql": "14.0.2",
"graphql-tag": "2.10.1",
"https-proxy-agent": "^2.2.1",
"isomorphic-unfetch": "^2.0.0",
"next": "latest",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment