diff --git a/examples/api-routes-apollo-server-and-client-auth/README.md b/examples/api-routes-apollo-server-and-client-auth/README.md new file mode 100644 index 0000000000000..3030c67d2af6d --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/README.md @@ -0,0 +1,49 @@ +# Apollo Server and Client Auth Example + +## 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 +``` + +Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download)): + +```bash +now +``` + +## The idea behind the 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 diff --git a/examples/api-routes-apollo-server-and-client-auth/apollo/client.js b/examples/api-routes-apollo-server-and-client-auth/apollo/client.js new file mode 100644 index 0000000000000..5fbdc6f7f249d --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/apollo/client.js @@ -0,0 +1,168 @@ +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 apolloClient = 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 ( + + + + ) + } + + // 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( + + ) + } 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 (!apolloClient) { + apolloClient = createApolloClient(ctx, initialState) + } + + return apolloClient +} + +/** + * 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') + const { context } = require('./context') + return new SchemaLink({ schema, context: context(ctx) }) + } else { + const { HttpLink } = require('apollo-link-http') + const { setContext } = require('apollo-link-context') + const { ApolloLink } = require('apollo-link') + const cookie = require('js-cookie') + + return ApolloLink.from([ + setContext(() => { + const token = cookie.get('token') + if (token) { + return { + headers: { + authorization: `Bearer ${token}`, + }, + } + } + }), + new HttpLink({ + uri: '/api/graphql', + credentials: 'same-origin', + }), + ]) + } +} diff --git a/examples/api-routes-apollo-server-and-client-auth/apollo/context.js b/examples/api-routes-apollo-server-and-client-auth/apollo/context.js new file mode 100644 index 0000000000000..4db16200df05a --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/apollo/context.js @@ -0,0 +1,10 @@ +import models from '../models' +import jwt from 'jsonwebtoken' +import getConfig from 'next/config' + +export const context = prevContext => ({ + ...prevContext, + ...getConfig(), + models, + jwt, +}) diff --git a/examples/api-routes-apollo-server-and-client-auth/apollo/resolvers.js b/examples/api-routes-apollo-server-and-client-auth/apollo/resolvers.js new file mode 100644 index 0000000000000..8d937373c09e5 --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/apollo/resolvers.js @@ -0,0 +1,71 @@ +import { + AuthenticationError, + ApolloError, + UserInputError, +} from 'apollo-server-micro' + +const getToken = headers => { + if (headers.authorization) { + return headers.authorization.replace(/bearer\s/i, '') + } else if (headers.cookie.includes('token=')) { + let part = headers.cookie.slice(headers.cookie.indexOf('token=') + 6) + return part.slice(0, part.indexOf(';')) + } +} + +export const resolvers = { + Query: { + async viewer(_parent, _args, context, _info) { + const token = getToken(context.req.headers) + if (token) { + try { + const { id, email } = context.jwt.verify( + token, + context.serverRuntimeConfig.JWT_SECRET + ) + + return await context.models.User.findOne({ where: { id, email } }) + } catch { + throw new AuthenticationError( + 'Authentication token is invalid, please log in' + ) + } + } + + return null + }, + }, + Mutation: { + async signUp(_parent, args, context, _info) { + const user = await context.models.User.create(args.input).catch( + error => + new ApolloError('ValidationError', 'VALIDATION_ERROR', { + errors: error.errors, + fields: error.fields, + }) + ) + + return { user } + }, + + async signIn(_parent, args, context, _info) { + const user = await context.models.User.findOne({ + where: { email: args.input.email }, + }) + + if (user && user.validPassword(args.input.password)) { + const token = context.jwt.sign( + { email: user.email, id: user.id, time: new Date() }, + context.serverRuntimeConfig.JWT_SECRET, + { + expiresIn: '6h', + } + ) + + return { user, token } + } + + throw new UserInputError('Invalid email and password combination') + }, + }, +} diff --git a/examples/api-routes-apollo-server-and-client-auth/apollo/schema.js b/examples/api-routes-apollo-server-and-client-auth/apollo/schema.js new file mode 100644 index 0000000000000..f6d70b7e86243 --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/apollo/schema.js @@ -0,0 +1,8 @@ +import { makeExecutableSchema } from 'graphql-tools' +import { typeDefs } from './type-defs' +import { resolvers } from './resolvers' + +export const schema = makeExecutableSchema({ + typeDefs, + resolvers, +}) diff --git a/examples/api-routes-apollo-server-and-client-auth/apollo/type-defs.js b/examples/api-routes-apollo-server-and-client-auth/apollo/type-defs.js new file mode 100644 index 0000000000000..5d20f58c85600 --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/apollo/type-defs.js @@ -0,0 +1,38 @@ +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! + token: String! + } + + type Query { + user(id: ID!): User! + users: [User]! + viewer: User + } + + type Mutation { + signUp(input: SignUpInput!): SignUpPayload! + signIn(input: SignInInput!): SignInPayload! + } +` diff --git a/examples/api-routes-apollo-server-and-client-auth/components/field.js b/examples/api-routes-apollo-server-and-client-auth/components/field.js new file mode 100644 index 0000000000000..2fa688740b6ef --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/components/field.js @@ -0,0 +1,22 @@ +export default function Field(props) { + return ( +
+ +
+ + {props.status ?

{props.status.message}

: undefined} +
+ ) +} diff --git a/examples/api-routes-apollo-server-and-client-auth/lib/auth.js b/examples/api-routes-apollo-server-and-client-auth/lib/auth.js new file mode 100644 index 0000000000000..166ead0c0e337 --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/lib/auth.js @@ -0,0 +1,66 @@ +import { useEffect } from 'react' +import Router from 'next/router' +import nextCookie from 'next-cookies' +import cookie from 'js-cookie' + +export const signin = ({ token }) => { + cookie.set('token', token, { expires: 0.25 }) + Router.push('/') +} + +export const auth = ctx => { + const { token } = nextCookie(ctx) + + // If there's no token, it means the user is not signed in. + if (!token) { + if (typeof window === 'undefined') { + ctx.res.writeHead(302, { Location: '/signin' }) + ctx.res.end() + } else { + Router.push('/signin') + } + } + + return token +} + +export const signout = () => { + cookie.remove('token') + // to support signing out from all windows + window.localStorage.setItem('signout', Date.now()) + Router.push('/signin') +} + +export const withAuthSync = WrappedComponent => { + const Wrapper = props => { + const syncSignout = event => { + if (event.key === 'signout') { + console.log('signed out from storage!') + Router.push('/signin') + } + } + + useEffect(() => { + window.addEventListener('storage', syncSignout) + + return () => { + window.removeEventListener('storage', syncSignout) + window.localStorage.removeItem('signout') + } + }, []) + + return + } + + Wrapper.getInitialProps = async ctx => { + const token = auth(ctx) + + const componentProps = + WrappedComponent.getInitialProps && + (await WrappedComponent.getInitialProps(ctx)) + + return { ...componentProps, token } + } + + return Wrapper +} diff --git a/examples/api-routes-apollo-server-and-client-auth/lib/form.js b/examples/api-routes-apollo-server-and-client-auth/lib/form.js new file mode 100644 index 0000000000000..79d4dd7b118e3 --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/lib/form.js @@ -0,0 +1,23 @@ +export function getValidationErrors(error) { + const validationErrors = {} + if (error.graphQLErrors) { + for (const graphQLError of error.graphQLErrors) { + if (graphQLError.message === 'ValidationError') { + return graphQLError.extensions.fields.reduce( + (newStatus, field, index) => ({ + ...newStatus, + [field]: graphQLError.extensions.errors[index], + }), + validationErrors + ) + } else if ( + graphQLError.extensions && + graphQLError.extensions.code === 'BAD_USER_INPUT' + ) { + return { '': graphQLError.message } + } + } + } + + return validationErrors +} diff --git a/examples/api-routes-apollo-server-and-client-auth/models/index.js b/examples/api-routes-apollo-server-and-client-auth/models/index.js new file mode 100644 index 0000000000000..08b4f56e52c2b --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/models/index.js @@ -0,0 +1,21 @@ +import Sequelize from 'sequelize' +import Message from './message' +import Thread from './thread' +import User from './user' + +export const sequelize = new Sequelize({ + dialect: 'sqlite', + storage: './database.sqlite3', +}) + +const models = { + Message: Message.init(sequelize, Sequelize), + Thread: Thread.init(sequelize, Sequelize), + User: User.init(sequelize, Sequelize), +} + +Object.values(models).forEach(model => { + if (typeof model.associate === 'function') model.associate(models) +}) + +export default models diff --git a/examples/api-routes-apollo-server-and-client-auth/models/message.js b/examples/api-routes-apollo-server-and-client-auth/models/message.js new file mode 100644 index 0000000000000..3ac3ea9938f78 --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/models/message.js @@ -0,0 +1,18 @@ +import Sequelize from 'sequelize' + +export default class Message extends Sequelize.Model { + static init(sequelize, DataTypes) { + return super.init( + { + body: { + type: DataTypes.TEXT, + }, + }, + { sequelize, modelName: 'message' } + ) + } + static associate(models) { + this.thread = this.belongsTo(models.Thread) + this.user = this.belongsTo(models.User) + } +} diff --git a/examples/api-routes-apollo-server-and-client-auth/models/thread.js b/examples/api-routes-apollo-server-and-client-auth/models/thread.js new file mode 100644 index 0000000000000..326c1a48ebecb --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/models/thread.js @@ -0,0 +1,11 @@ +import Sequelize from 'sequelize' + +export default class Thread extends Sequelize.Model { + static init(sequelize, DataTypes) { + return super.init({}, { sequelize, modelName: 'thread' }) + } + static associate(models) { + this.users = this.hasMany(models.User) + this.messages = this.hasMany(models.Message, { onDelete: 'CASCADE' }) + } +} diff --git a/examples/api-routes-apollo-server-and-client-auth/models/user.js b/examples/api-routes-apollo-server-and-client-auth/models/user.js new file mode 100644 index 0000000000000..d418301b3f84f --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/models/user.js @@ -0,0 +1,44 @@ +import bcrypt from 'bcrypt' +import Sequelize from 'sequelize' + +export default class User extends Sequelize.Model { + static init(sequelize, DataTypes) { + return super.init( + { + email: { + type: DataTypes.STRING, + unique: true, + allowNull: false, + }, + hashedPassword: { + type: DataTypes.STRING, + allowNull: false, + set(value) { + // don't allow developer to set hashedPassword + // force them to use password and have it delegate to hashedPassword + throw new Error('use `password` setter instead') + }, + }, + password: { + type: DataTypes.VIRTUAL, + set(value) { + const salt = bcrypt.genSaltSync() + this.setDataValue('hashedPassword', bcrypt.hashSync(value, salt)) + }, + }, + }, + { + sequelize, + modelName: 'user', + } + ) + } + + static associate(models) { + this.threads = this.belongsTo(models.Thread) + } + + validPassword(password) { + return bcrypt.compareSync(password, this.getDataValue('hashedPassword')) + } +} diff --git a/examples/api-routes-apollo-server-and-client-auth/next.config.js b/examples/api-routes-apollo-server-and-client-auth/next.config.js new file mode 100644 index 0000000000000..35db685d842d2 --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/next.config.js @@ -0,0 +1,5 @@ +module.exports = { + serverRuntimeConfig: { + JWT_SECRET: 'changeme', + }, +} diff --git a/examples/api-routes-apollo-server-and-client-auth/package.json b/examples/api-routes-apollo-server-and-client-auth/package.json new file mode 100644 index 0000000000000..762b7502892d8 --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/package.json @@ -0,0 +1,35 @@ +{ + "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-context": "1.0.19", + "apollo-link-http": "1.5.16", + "apollo-link-schema": "1.2.4", + "apollo-server-micro": "2.9.15", + "apollo-utilities": "^1.3.2", + "bcrypt": "3.0.7", + "graphql": "^14.0.2", + "graphql-tag": "2.10.1", + "js-cookie": "2.2.1", + "jsonwebtoken": "8.5.1", + "next": "latest", + "next-cookies": "2.0.3", + "prop-types": "^15.6.2", + "react": "^16.7.0", + "react-dom": "^16.7.0", + "sequelize": "5.21.3", + "sqlite3": "4.1.1" + }, + "author": "", + "license": "ISC" +} diff --git a/examples/api-routes-apollo-server-and-client-auth/pages/about.js b/examples/api-routes-apollo-server-and-client-auth/pages/about.js new file mode 100644 index 0000000000000..37a11a9e09651 --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/pages/about.js @@ -0,0 +1,11 @@ +import Link from 'next/link' + +export default () => ( +
+ This is a static page goto{' '} + + dynamic + {' '} + page. +
+) diff --git a/examples/api-routes-apollo-server-and-client-auth/pages/api/graphql.js b/examples/api-routes-apollo-server-and-client-auth/pages/api/graphql.js new file mode 100644 index 0000000000000..738edf60ba0db --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/pages/api/graphql.js @@ -0,0 +1,16 @@ +import { ApolloServer } from 'apollo-server-micro' +import { context } from '../../apollo/context' +import { schema } from '../../apollo/schema' +import { sequelize } from '../../models' + +const apolloServer = new ApolloServer({ schema, context }) + +sequelize.sync() + +export const config = { + api: { + bodyParser: false, + }, +} + +export default apolloServer.createHandler({ path: '/api/graphql' }) diff --git a/examples/api-routes-apollo-server-and-client-auth/pages/index.js b/examples/api-routes-apollo-server-and-client-auth/pages/index.js new file mode 100644 index 0000000000000..661209cac551e --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/pages/index.js @@ -0,0 +1,34 @@ +import { withApollo } from '../apollo/client' +import gql from 'graphql-tag' +import Link from 'next/link' +import { useQuery } from '@apollo/react-hooks' +import { withAuthSync, signout } from '../lib/auth' + +const ViewerQuery = gql` + query ViewerQuery { + viewer { + id + email + } + } +` + +const Index = () => { + const { data } = useQuery(ViewerQuery) + + if (data && data.viewer) { + return ( +
+ You're signed in as {data.viewer.email} goto{' '} + + static + {' '} + page. or +
+ ) + } + + return

Loading...

+} + +export default withAuthSync(withApollo(Index)) diff --git a/examples/api-routes-apollo-server-and-client-auth/pages/signin.js b/examples/api-routes-apollo-server-and-client-auth/pages/signin.js new file mode 100644 index 0000000000000..5b86dc593eb0c --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/pages/signin.js @@ -0,0 +1,75 @@ +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 { getValidationErrors } from '../lib/form' +import { signin } from '../lib/auth' + +const SignInMutation = gql` + mutation SignInMutation($email: String!, $password: String!) { + signIn(input: { email: $email, password: $password }) { + user { + id + email + } + token + } + } +` + +function SignIn() { + const [signIn] = useMutation(SignInMutation) + const [status, setStatus] = React.useState({}) + 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.token) { + signin({ token: data.signIn.token }) + } + } catch (error) { + setStatus(getValidationErrors(error)) + } + } + + return ( + <> +

Sign In

+
+ {'' in status ?

{status['']}

: undefined} + + + or{' '} + + Sign up + + + + ) +} + +export default withApollo(SignIn) diff --git a/examples/api-routes-apollo-server-and-client-auth/pages/signup.js b/examples/api-routes-apollo-server-and-client-auth/pages/signup.js new file mode 100644 index 0000000000000..0b0a7b5ea14fb --- /dev/null +++ b/examples/api-routes-apollo-server-and-client-auth/pages/signup.js @@ -0,0 +1,69 @@ +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 { getValidationErrors } from '../lib/form' + +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 [status, setStatus] = React.useState({}) + async function handleSubmit(event) { + event.preventDefault() + const emailElement = event.currentTarget.elements.email + const passwordElement = event.currentTarget.elements.password + + try { + const res = await signUp({ + variables: { + email: emailElement.value, + password: passwordElement.value, + }, + }) + } catch (error) { + setStatus(getValidationErrors(error)) + } + } + + return ( + <> +

Sign Up

+
+ + + or{' '} + + Sign in + + + + ) +} + +export default withApollo(SignUp)