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 = () => { ...@@ -47,7 +47,6 @@ const RegisterBox = () => {
<form <form
onSubmit={e => { onSubmit={e => {
e.preventDefault() e.preventDefault()
e.stopPropagation()
create({ create({
variables: { variables: {
......
...@@ -19,6 +19,8 @@ const SigninBox = () => { ...@@ -19,6 +19,8 @@ const SigninBox = () => {
const onCompleted = data => { const onCompleted = data => {
// Store the token in cookie // Store the token in cookie
document.cookie = cookie.serialize('token', data.signinUser.token, { document.cookie = cookie.serialize('token', data.signinUser.token, {
sameSite: true,
path: '/',
maxAge: 30 * 24 * 60 * 60 // 30 days maxAge: 30 * 24 * 60 * 60 // 30 days
}) })
// Force a reload of all the current queries now that the user is // Force a reload of all the current queries now that the user is
...@@ -45,7 +47,6 @@ const SigninBox = () => { ...@@ -45,7 +47,6 @@ const SigninBox = () => {
<form <form
onSubmit={e => { onSubmit={e => {
e.preventDefault() e.preventDefault()
e.stopPropagation()
signinUser({ signinUser({
variables: { variables: {
......
import React, { useMemo } from 'react' import React, { useMemo } from 'react'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import cookie from 'cookie' import cookie from 'cookie'
import { ApolloProvider } from '@apollo/react-hooks'
import Head from 'next/head' 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 { setContext } from 'apollo-link-context'
import { ApolloProvider } from '@apollo/react-hooks'
import fetch from 'isomorphic-unfetch' import fetch from 'isomorphic-unfetch'
/** /**
...@@ -15,7 +17,7 @@ import fetch from 'isomorphic-unfetch' ...@@ -15,7 +17,7 @@ import fetch from 'isomorphic-unfetch'
* @param {Object} [config] * @param {Object} [config]
* @param {Boolean} [config.ssr=true] * @param {Boolean} [config.ssr=true]
*/ */
export function withApollo (PageComponent) { export function withApollo (PageComponent, { ssr = true } = {}) {
const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => { const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
const client = useMemo(() => { const client = useMemo(() => {
// We pass in the apolloClient directly when using getDataFromTree // We pass in the apolloClient directly when using getDataFromTree
...@@ -24,11 +26,7 @@ export function withApollo (PageComponent) { ...@@ -24,11 +26,7 @@ export function withApollo (PageComponent) {
} }
// Otherwise initClient using apolloState // Otherwise initClient using apolloState
return initApolloClient(apolloState, { return initApolloClient(apolloState, { getToken })
getToken: () => {
return parseCookies().token
}
})
}, []) }, [])
return ( return (
<ApolloProvider client={client}> <ApolloProvider client={client}>
...@@ -59,15 +57,16 @@ export function withApollo (PageComponent) { ...@@ -59,15 +57,16 @@ export function withApollo (PageComponent) {
} }
} }
if (ssr || PageComponent.getInitialProps) {
WithApollo.getInitialProps = async ctx => { WithApollo.getInitialProps = async ctx => {
const { AppTree, req, res } = ctx const { AppTree } = ctx
// Run all GraphQL queries in the component tree // Run all GraphQL queries in the component tree
// and extract the resulting data // and extract the resulting data
const apolloClient = (ctx.apolloClient = initApolloClient( const apolloClient = (ctx.apolloClient = initApolloClient(
{}, {},
{ {
getToken: () => parseCookies(req).token getToken: () => getToken(ctx.req)
} }
)) ))
...@@ -75,14 +74,15 @@ export function withApollo (PageComponent) { ...@@ -75,14 +74,15 @@ export function withApollo (PageComponent) {
? await PageComponent.getInitialProps(ctx) ? await PageComponent.getInitialProps(ctx)
: {} : {}
if (res && res.finished) { // Only on the server
if (typeof window === 'undefined') {
// When redirecting, the response is finished. // When redirecting, the response is finished.
// No point in continuing to render // No point in continuing to render
if (ctx.res && ctx.res.finished) {
return {} return {}
} }
// Get apolloState on the server (needed for ssr) if (ssr) {
if (typeof window === 'undefined') {
try { try {
// Run all GraphQL queries // Run all GraphQL queries
const { getDataFromTree } = await import('@apollo/react-ssr') const { getDataFromTree } = await import('@apollo/react-ssr')
...@@ -100,6 +100,7 @@ export function withApollo (PageComponent) { ...@@ -100,6 +100,7 @@ export function withApollo (PageComponent) {
// https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
console.error('Error while running `getDataFromTree`', error) console.error('Error while running `getDataFromTree`', error)
} }
}
// getDataFromTree does not call componentWillUnmount // getDataFromTree does not call componentWillUnmount
// head side effect therefore need to be cleared manually // head side effect therefore need to be cleared manually
...@@ -114,6 +115,7 @@ export function withApollo (PageComponent) { ...@@ -114,6 +115,7 @@ export function withApollo (PageComponent) {
apolloState apolloState
} }
} }
}
return WithApollo return WithApollo
} }
...@@ -164,7 +166,7 @@ function createApolloClient (initialState = {}, { getToken }) { ...@@ -164,7 +166,7 @@ function createApolloClient (initialState = {}, { getToken }) {
fetchOptions fetchOptions
}) })
const authLink = setContext((_, { headers }) => { const authLink = setContext((request, { headers }) => {
const token = getToken() const token = getToken()
return { return {
headers: { headers: {
...@@ -175,21 +177,18 @@ function createApolloClient (initialState = {}, { getToken }) { ...@@ -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 // 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({ return new ApolloClient({
connectToDevTools: isBrowser, ssrMode: typeof window === 'undefined', // Disables forceFetch on the server (so queries are only run once)
ssrMode: !isBrowser, // Disables forceFetch on the server (so queries are only run once)
link: authLink.concat(httpLink), link: authLink.concat(httpLink),
cache: new InMemoryCache().restore(initialState) cache: new InMemoryCache().restore(initialState)
}) })
} }
/** /**
* Cookie parser that works on the * Get the user token from cookie
* server and on the client
* @param {Object} req * @param {Object} req
* @param {Object} config
*/ */
function parseCookies (req, config = {}) { function getToken (req) {
return cookie.parse(req ? req.headers.cookie || '' : document.cookie, config) const cookies = cookie.parse(req ? req.headers.cookie || '' : document.cookie)
return cookies.token
} }
...@@ -11,10 +11,13 @@ ...@@ -11,10 +11,13 @@
"dependencies": { "dependencies": {
"@apollo/react-hooks": "^3.0.1", "@apollo/react-hooks": "^3.0.1",
"@apollo/react-ssr": "^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-context": "^1.0.8",
"apollo-link-http": "1.5.15",
"cookie": "^0.3.1", "cookie": "^0.3.1",
"graphql": "14.0.2", "graphql": "14.0.2",
"graphql-tag": "2.10.1",
"https-proxy-agent": "^2.2.1", "https-proxy-agent": "^2.2.1",
"isomorphic-unfetch": "^2.0.0", "isomorphic-unfetch": "^2.0.0",
"next": "latest", "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