Commit a356d2f6 authored by Aaron Reisman's avatar Aaron Reisman Committed by Luis Alvarez D

Add Apollo Server and Client Auth Example (#9913)

* Add Apollo Server and Client Auth Example

* Some updates

* Updated docs
Co-authored-by: 's avatarLuis Alvarez D. <luis@zeit.co>
parent bc139c29
# Apollo Server and Client Auth Example
[Apollo](https://www.apollographql.com/client/) is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server.
In this simple example, we integrate Apollo seamlessly with Next by wrapping our _pages/\_app.js_ inside a [higher-order component (HOC)](https://facebook.github.io/react/docs/higher-order-components.html). Using the HOC pattern we're able to pass down a central store of query result data created by Apollo into our React component hierarchy defined inside each page of our Next application.
On initial page load, while on the server and inside `getInitialProps`, we invoke the Apollo method, [`getDataFromTree`](https://www.apollographql.com/docs/react/api/react-ssr/#getdatafromtree). This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized.
Note: Do not be alarmed that you see two renders being executed. Apollo recursively traverses the React render tree looking for Apollo query components. When it has done that, it fetches all these queries and then passes the result to a cache. This cache is then used to render the data on the server side (another React render).
https://www.apollographql.com/docs/react/api/react-ssr/#getdatafromtree
## Deploy your own
Deploy the example using [ZEIT Now](https://zeit.co/now):
[![Deploy with ZEIT Now](https://zeit.co/button)](https://zeit.co/new/project?template=https://github.com/zeit/next.js/tree/canary/examples/api-routes-apollo-server-and-client-auth)
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npx create-next-app --example api-routes-apollo-server-and-client-auth api-routes-apollo-server-and-client-auth-app
# or
yarn create next-app --example api-routes-apollo-server-and-client-auth api-routes-apollo-server-and-client-auth-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/api-routes-apollo-server-and-client-auth
cd api-routes-apollo-server-and-client-auth
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
> If you have issues installing `bcrypt`, follow this instructions: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download)):
```bash
now
```
import React from 'react'
import Head from 'next/head'
import { ApolloProvider } from '@apollo/react-hooks'
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
let globalApolloClient = null
/**
* 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/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
return new ApolloClient({
ssrMode,
link: createIsomorphLink(ctx),
cache,
})
}
function createIsomorphLink(ctx) {
if (typeof window === 'undefined') {
const { SchemaLink } = require('apollo-link-schema')
const { schema } = require('./schema')
return new SchemaLink({ schema, context: ctx })
} else {
const { HttpLink } = require('apollo-link-http')
return new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin',
})
}
}
import { AuthenticationError, UserInputError } from 'apollo-server-micro'
import cookie from 'cookie'
import jwt from 'jsonwebtoken'
import getConfig from 'next/config'
import bcrypt from 'bcrypt'
import v4 from 'uuid/v4'
const JWT_SECRET = getConfig().serverRuntimeConfig.JWT_SECRET
const users = []
function createUser(data) {
const salt = bcrypt.genSaltSync()
return {
id: v4(),
email: data.email,
hashedPassword: bcrypt.hashSync(data.password, salt),
}
}
function validPassword(user, password) {
return bcrypt.compareSync(password, user.hashedPassword)
}
export const resolvers = {
Query: {
async viewer(_parent, _args, context, _info) {
const { token } = cookie.parse(context.req.headers.cookie ?? '')
if (token) {
try {
const { id, email } = jwt.verify(token, JWT_SECRET)
return users.find(user => user.id === id && user.email === email)
} catch {
throw new AuthenticationError(
'Authentication token is invalid, please log in'
)
}
}
},
},
Mutation: {
async signUp(_parent, args, _context, _info) {
const user = createUser(args.input)
users.push(user)
return { user }
},
async signIn(_parent, args, context, _info) {
const user = users.find(user => user.email === args.input.email)
if (user && validPassword(user, args.input.password)) {
const token = jwt.sign(
{ email: user.email, id: user.id, time: new Date() },
JWT_SECRET,
{
expiresIn: '6h',
}
)
context.res.setHeader(
'Set-Cookie',
cookie.serialize('token', token, {
httpOnly: true,
maxAge: 6 * 60 * 60,
path: '/',
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
})
)
return { user }
}
throw new UserInputError('Invalid email and password combination')
},
async signOut(_parent, _args, context, _info) {
context.res.setHeader(
'Set-Cookie',
cookie.serialize('token', '', {
httpOnly: true,
maxAge: -1,
path: '/',
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
})
)
return true
},
},
}
import { makeExecutableSchema } from 'graphql-tools'
import { typeDefs } from './type-defs'
import { resolvers } from './resolvers'
export const schema = makeExecutableSchema({
typeDefs,
resolvers,
})
import gql from 'graphql-tag'
export const typeDefs = gql`
type User {
id: ID!
email: String!
}
input SignUpInput {
email: String!
password: String!
}
input SignInInput {
email: String!
password: String!
}
type SignUpPayload {
user: User!
}
type SignInPayload {
user: User!
}
type Query {
user(id: ID!): User!
users: [User]!
viewer: User
}
type Mutation {
signUp(input: SignUpInput!): SignUpPayload!
signIn(input: SignInInput!): SignInPayload!
signOut: Boolean!
}
`
export default function Field(props) {
return (
<div>
<label
id={[props.name, 'label'].join('-')}
htmlFor={[props.name, 'input'].join('-')}
>
{props.label}{' '}
{props.required ? <span title="Required">*</span> : undefined}
</label>
<br />
<input
autoComplete={props.autoComplete}
id={[props.name, 'input'].join('-')}
name={props.name}
required={props.required}
type={props.type}
/>
</div>
)
}
export function getErrorMessage(error) {
if (error.graphQLErrors) {
for (const graphQLError of error.graphQLErrors) {
if (
graphQLError.extensions &&
graphQLError.extensions.code === 'BAD_USER_INPUT'
) {
return graphQLError.message
}
}
}
return error.message
}
module.exports = {
serverRuntimeConfig: {
JWT_SECRET: 'changeme',
},
}
{
"name": "with-apollo",
"version": "2.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@apollo/react-common": "3.1.3",
"@apollo/react-hooks": "3.1.3",
"@apollo/react-ssr": "3.1.3",
"apollo-cache-inmemory": "1.6.5",
"apollo-client": "2.6.8",
"apollo-link-http": "1.5.16",
"apollo-link-schema": "1.2.4",
"apollo-server-micro": "2.9.16",
"apollo-utilities": "^1.3.2",
"bcrypt": "3.0.7",
"cookie": "0.4.0",
"graphql": "^14.0.2",
"graphql-tag": "2.10.1",
"jsonwebtoken": "8.5.1",
"next": "latest",
"prop-types": "^15.6.2",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"uuid": "3.4.0"
},
"author": "",
"license": "ISC"
}
import Link from 'next/link'
export default () => (
<div>
This is a static page goto{' '}
<Link href="/">
<a>dynamic</a>
</Link>{' '}
page.
</div>
)
import { ApolloServer } from 'apollo-server-micro'
import { schema } from '../../apollo/schema'
const apolloServer = new ApolloServer({
schema,
context(ctx) {
return ctx
},
})
export const config = {
api: {
bodyParser: false,
},
}
export default apolloServer.createHandler({ path: '/api/graphql' })
import { withApollo } from '../apollo/client'
import gql from 'graphql-tag'
import Link from 'next/link'
import { useQuery } from '@apollo/react-hooks'
import { useRouter } from 'next/router'
const ViewerQuery = gql`
query ViewerQuery {
viewer {
id
email
}
}
`
const Index = () => {
const router = useRouter()
const { data, loading } = useQuery(ViewerQuery)
if (
loading === false &&
data.viewer === null &&
typeof window !== 'undefined'
) {
router.push('/signin')
}
if (data && data.viewer) {
return (
<div>
You're signed in as {data.viewer.email} goto{' '}
<Link href="/about">
<a>static</a>
</Link>{' '}
page. or{' '}
<Link href="/signout">
<a>signout</a>
</Link>
</div>
)
}
return <p>Loading...</p>
}
export default withApollo(Index)
import React from 'react'
import Link from 'next/link'
import { withApollo } from '../apollo/client'
import gql from 'graphql-tag'
import { useMutation } from '@apollo/react-hooks'
import Field from '../components/field'
import { getErrorMessage } from '../lib/form'
import { useRouter } from 'next/router'
const SignInMutation = gql`
mutation SignInMutation($email: String!, $password: String!) {
signIn(input: { email: $email, password: $password }) {
user {
id
email
}
}
}
`
function SignIn() {
const [signIn] = useMutation(SignInMutation)
const [errorMsg, setErrorMsg] = React.useState()
const router = useRouter()
async function handleSubmit(event) {
event.preventDefault()
const emailElement = event.currentTarget.elements.email
const passwordElement = event.currentTarget.elements.password
try {
const { data } = await signIn({
variables: {
email: emailElement.value,
password: passwordElement.value,
},
})
if (data.signIn.user) {
router.push('/')
}
} catch (error) {
setErrorMsg(getErrorMessage(error))
}
}
return (
<>
<h1>Sign In</h1>
<form onSubmit={handleSubmit}>
{errorMsg && <p>{errorMsg}</p>}
<Field
name="email"
type="email"
autoComplete="email"
required
label="Email"
/>
<Field
name="password"
type="password"
autoComplete="password"
required
label="Password"
/>
<button type="submit">Sign in</button> or{' '}
<Link href="signup">
<a>Sign up</a>
</Link>
</form>
</>
)
}
export default withApollo(SignIn)
import React from 'react'
import { useMutation } from '@apollo/react-hooks'
import gql from 'graphql-tag'
import { useRouter } from 'next/router'
import { withApollo } from '../apollo/client'
const SignOutMutation = gql`
mutation SignOutMutation {
signOut
}
`
function SignOut() {
const router = useRouter()
const [signOut] = useMutation(SignOutMutation)
React.useEffect(() => {
if (typeof window !== 'undefined') {
signOut().then(() => {
router.push('/signin')
})
}
}, [signOut, router])
return <p>Signing out...</p>
}
export default withApollo(SignOut)
import React from 'react'
import Link from 'next/link'
import { withApollo } from '../apollo/client'
import gql from 'graphql-tag'
import { useMutation } from '@apollo/react-hooks'
import Field from '../components/field'
import { getErrorMessage } from '../lib/form'
import { useRouter } from 'next/router'
const SignUpMutation = gql`
mutation SignUpMutation($email: String!, $password: String!) {
signUp(input: { email: $email, password: $password }) {
user {
id
email
}
}
}
`
function SignUp() {
const [signUp] = useMutation(SignUpMutation)
const [errorMsg, setErrorMsg] = React.useState()
const router = useRouter()
async function handleSubmit(event) {
event.preventDefault()
const emailElement = event.currentTarget.elements.email
const passwordElement = event.currentTarget.elements.password
try {
await signUp({
variables: {
email: emailElement.value,
password: passwordElement.value,
},
})
router.push('/signin')
} catch (error) {
setErrorMsg(getErrorMessage(error))
}
}
return (
<>
<h1>Sign Up</h1>
<form onSubmit={handleSubmit}>
{errorMsg && <p>{errorMsg}</p>}
<Field
name="email"
type="email"
autoComplete="email"
required
label="Email"
/>
<Field
name="password"
type="password"
autoComplete="password"
required
label="Password"
/>
<button type="submit">Sign up</button> or{' '}
<Link href="signin">
<a>Sign in</a>
</Link>
</form>
</>
)
}
export default withApollo(SignUp)
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