Unverified Commit 081b8fba authored by Horacio Valencia's avatar Horacio Valencia Committed by GitHub

Updates Apollo Server Examples to use Apollo Server 4 & @as-integrations/next (#42771)

Closes https://github.com/vercel/next.js/issues/42769

## Description 

This PR address https://github.com/vercel/next.js/issues/42769 by updating the `api-routes-apollo-server`, `api-routes-apollo-server-and-client` and `api-routes-apollo-server-and-client-auth` examples to use Apollo Server 4 and [@as-integrations/next](https://github.com/apollo-server-integrations/apollo-server-integration-next), which is the Apollo Server Next integration package. The PR also updates the three examples to use Typescript. The functionality of the examples is the same.


## Documentation / Examples
- [X] Make sure the linting passes by running `pnpm build && pnpm lint`
- [X] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)


closes https://github.com/vercel/next.js/pull/33545
closes https://github.com/vercel/next.js/pull/30082
closes https://github.com/vercel/next.js/issues/21984
closes #10413
parent 0bc94466
# Apollo Server and Client Auth Example # 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. [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. The integration with Next and Apollo Server is implemented using the [apollo-server-integration-next](https://github.com/apollo-server-integrations/apollo-server-integration-next) community package.
In this simple example, we integrate Apollo seamlessly with [Next.js data fetching methods](https://nextjs.org/docs/basic-features/data-fetching) to fetch queries in the server and hydrate them in the browser. In this simple example, we integrate Apollo seamlessly with [Next.js data fetching methods](https://nextjs.org/docs/basic-features/data-fetching) to fetch queries in the server and hydrate them in the browser.
......
import { useMemo } from 'react' import { useMemo } from 'react'
import { ApolloClient, InMemoryCache } from '@apollo/client' import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client'
import { SchemaLink } from '@apollo/client/link/schema'
import { schema } from '../apollo/schema'
import merge from 'deepmerge' import merge from 'deepmerge'
let apolloClient let apolloClient
function createIsomorphLink() { function createIsomorphLink() {
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
const { SchemaLink } = require('@apollo/client/link/schema')
const { schema } = require('./schema')
return new SchemaLink({ schema }) return new SchemaLink({ schema })
} else { } else {
const { HttpLink } = require('@apollo/client/link/http')
return new HttpLink({ return new HttpLink({
uri: '/api/graphql', uri: '/api/graphql',
credentials: 'same-origin', credentials: 'same-origin',
......
import { AuthenticationError, UserInputError } from 'apollo-server-micro'
import { createUser, findUser, validatePassword } from '../lib/user' import { createUser, findUser, validatePassword } from '../lib/user'
import { setLoginSession, getLoginSession } from '../lib/auth' import { setLoginSession, getLoginSession } from '../lib/auth'
import { removeTokenCookie } from '../lib/auth-cookies' import { removeTokenCookie } from '../lib/auth-cookies'
import { GraphQLError } from 'graphql'
export const resolvers = { export const resolvers = {
Query: { Query: {
async viewer(_parent, _args, context, _info) { async viewer(_root, _args, context, _info) {
try { try {
const session = await getLoginSession(context.req) const session = await getLoginSession(context.req)
...@@ -13,8 +13,13 @@ export const resolvers = { ...@@ -13,8 +13,13 @@ export const resolvers = {
return findUser({ email: session.email }) return findUser({ email: session.email })
} }
} catch (error) { } catch (error) {
throw new AuthenticationError( throw new GraphQLError(
'Authentication token is invalid, please log in' 'Authentication token is invalid, please log in',
{
extensions: {
code: 'UNAUTHENTICATED',
},
}
) )
} }
}, },
...@@ -38,7 +43,7 @@ export const resolvers = { ...@@ -38,7 +43,7 @@ export const resolvers = {
return { user } return { user }
} }
throw new UserInputError('Invalid email and password combination') throw new GraphQLError('Invalid email and password combination')
}, },
async signOut(_parent, _args, context, _info) { async signOut(_parent, _args, context, _info) {
removeTokenCookie(context.res) removeTokenCookie(context.res)
......
import { makeExecutableSchema } from 'graphql-tools' import { makeExecutableSchema } from '@graphql-tools/schema'
import { typeDefs } from './type-defs' import { typeDefs } from './type-defs'
import { resolvers } from './resolvers' import { resolvers } from './resolvers'
......
...@@ -6,16 +6,24 @@ ...@@ -6,16 +6,24 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@apollo/client": "^3.0.2", "@apollo/client": "^3.7.1",
"@apollo/server": "^4.1.1",
"@as-integrations/next": "^1.1.0",
"@graphql-tools/schema": "^9.0.9",
"graphql": "^16.6.0",
"@hapi/iron": "6.0.0", "@hapi/iron": "6.0.0",
"apollo-server-micro": "^2.14.2",
"cookie": "^0.4.1", "cookie": "^0.4.1",
"deepmerge": "4.2.2", "deepmerge": "4.2.2",
"graphql": "^14.0.2",
"next": "latest", "next": "latest",
"prop-types": "^15.6.2", "prop-types": "^15.6.2",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"uuid": "8.1.0" "uuid": "8.1.0"
},
"devDependencies": {
"@types/node": "^18.0.2",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"typescript": "^4.7.4"
} }
} }
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 { ApolloServer } from '@apollo/server'
import { startServerAndCreateNextHandler } from '@as-integrations/next'
import { NextApiRequest, NextApiResponse } from 'next'
import { schema } from '../../apollo/schema'
type ExampleContext = {
req: NextApiRequest
res: NextApiResponse
}
const apolloServer = new ApolloServer<ExampleContext>({ schema })
export default startServerAndCreateNextHandler(apolloServer, {
context: async (req, res) => ({ req, res }),
})
...@@ -32,8 +32,9 @@ const Index = () => { ...@@ -32,8 +32,9 @@ const Index = () => {
if (viewer) { if (viewer) {
return ( return (
<div> <div>
You're signed in as {viewer.email} goto <Link href="/about">about</Link>{' '} You're signed in as {viewer.email}. Go to{' '}
page. or <Link href="/signout">signout</Link> <Link href="/about">about</Link> page or{' '}
<Link href="/signout">signout</Link>.
</div> </div>
) )
} }
......
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "pages/about.js"],
"exclude": ["node_modules"]
}
# Apollo Server and Client Example # Apollo Server and Client 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. [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. The integration with Next and Apollo Server is implemented using the [apollo-server-integration-next](https://github.com/apollo-server-integrations/apollo-server-integration-next) community package.
In this simple example, we integrate Apollo seamlessly with [Next.js data fetching methods](https://nextjs.org/docs/basic-features/data-fetching) to fetch queries in the server and hydrate them in the browser. In this simple example, we integrate Apollo seamlessly with [Next.js data fetching methods](https://nextjs.org/docs/basic-features/data-fetching) to fetch queries in the server and hydrate them in the browser.
......
import { useMemo } from 'react' import { useMemo } from 'react'
import { ApolloClient, InMemoryCache } from '@apollo/client' import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client'
import { SchemaLink } from '@apollo/client/link/schema'
import { schema } from '../apollo/schema'
import merge from 'deepmerge' import merge from 'deepmerge'
let apolloClient let apolloClient
function createIsomorphLink() { function createIsomorphLink() {
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
const { SchemaLink } = require('@apollo/client/link/schema')
const { schema } = require('./schema')
return new SchemaLink({ schema }) return new SchemaLink({ schema })
} else { } else {
const { HttpLink } = require('@apollo/client/link/http')
return new HttpLink({ return new HttpLink({
uri: '/api/graphql', uri: '/api/graphql',
credentials: 'same-origin', credentials: 'same-origin',
......
export const resolvers = { export const resolvers = {
Query: { Query: {
viewer(_parent, _args, _context, _info) { viewer() {
return { id: 1, name: 'John Smith', status: 'cached' } return { id: 1, name: 'John Smith', status: 'cached' }
}, },
}, },
......
import { makeExecutableSchema } from 'graphql-tools' import { makeExecutableSchema } from '@graphql-tools/schema'
import { typeDefs } from './type-defs' import { typeDefs } from './type-defs'
import { resolvers } from './resolvers' import { resolvers } from './resolvers'
......
...@@ -6,13 +6,20 @@ ...@@ -6,13 +6,20 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@apollo/client": "^3.0.2", "@apollo/client": "^3.7.1",
"apollo-server-micro": "^2.14.2", "@apollo/server": "^4.1.1",
"@as-integrations/next": "^1.1.0",
"@graphql-tools/schema": "^9.0.9",
"deepmerge": "4.2.2", "deepmerge": "4.2.2",
"graphql": "^14.0.2", "graphql": "^16.6.0",
"next": "latest", "next": "latest",
"prop-types": "^15.6.2",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0" "react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^18.0.2",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"typescript": "^4.7.4"
} }
} }
import { ApolloServer } from 'apollo-server-micro' import { ApolloServer } from '@apollo/server'
import { startServerAndCreateNextHandler } from '@as-integrations/next'
import { schema } from '../../apollo/schema' import { schema } from '../../apollo/schema'
const apolloServer = new ApolloServer({ schema }) const apolloServer = new ApolloServer({ schema })
export const config = { export default startServerAndCreateNextHandler(apolloServer)
api: {
bodyParser: false,
},
}
export default apolloServer.createHandler({ path: '/api/graphql' })
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
# Consume local Apollo GraphQL schema to create Static Generation export # Consume local Apollo GraphQL schema to create Static Generation export
Next.js ships with two forms of pre-rendering: [Static Generation](https://nextjs.org/docs/basic-features/pages#static-generation-recommended) and [Server-side Rendering](https://nextjs.org/docs/basic-features/pages#server-side-rendering). This example shows how to perform Static Generation using a local [Apollo GraphQL](https://www.apollographql.com/docs/apollo-server/) schema within [getStaticProps](https://nextjs.org/docs/basic-features/data-fetching/get-static-props) and [getStaticPaths](https://nextjs.org/docs/basic-features/data-fetching/get-static-paths.md). The end result is a Next.js application that uses one Apollo GraphQL schema to generate static pages at build time and also serve a GraphQL [API Route](https://nextjs.org/docs/api-routes/introduction) at runtime. Next.js ships with two forms of pre-rendering: [Static Generation](https://nextjs.org/docs/basic-features/pages#static-generation-recommended) and [Server-side Rendering](https://nextjs.org/docs/basic-features/pages#server-side-rendering). This example shows how to perform Static Generation using a local [Apollo GraphQL Server ](https://www.apollographql.com/docs/apollo-server/) schema within [getStaticProps](https://nextjs.org/docs/basic-features/data-fetching/get-static-props) and [getStaticPaths](https://nextjs.org/docs/basic-features/data-fetching/get-static-paths.md). The end result is a Next.js application that uses one Apollo GraphQL schema to generate static pages at build time and also serve a GraphQL [API Route](https://nextjs.org/docs/api-routes/introduction) at runtime. The integration with Next and Apollo Server is implemented using the [apollo-server-integration-next](https://github.com/apollo-server-integrations/apollo-server-integration-next) community package.
## Deploy your own ## Deploy your own
......
...@@ -7,10 +7,19 @@ ...@@ -7,10 +7,19 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"apollo-server-micro": "2.13.1", "@apollo/server": "^4.1.1",
"graphql": "15.0.0", "@as-integrations/next": "^1.1.0",
"@graphql-tools/schema": "^9.0.9",
"graphql": "16.6.0",
"graphql-tag": "^2.12.6",
"next": "latest", "next": "latest",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0" "react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^18.0.0",
"@types/react": "^18.0.14",
"@types/react-dom": "^18.0.5",
"typescript": "^4.7.4"
} }
} }
...@@ -29,13 +29,14 @@ export async function getStaticProps(context) { ...@@ -29,13 +29,14 @@ export async function getStaticProps(context) {
} }
export async function getStaticPaths() { export async function getStaticPaths() {
const { users } = await queryGraphql(` const { users } = (await queryGraphql(`
query { query {
users { users {
username username
} }
} }
`) `)) as { users: { username: string }[] }
return { return {
paths: users.map(({ username }) => ({ paths: users.map(({ username }) => ({
params: { username }, params: { username },
......
import { ApolloServer, gql, makeExecutableSchema } from 'apollo-server-micro' import { ApolloServer } from '@apollo/server'
import { startServerAndCreateNextHandler } from '@as-integrations/next'
import { makeExecutableSchema } from '@graphql-tools/schema'
import { gql } from 'graphql-tag'
const typeDefs = gql` const typeDefs = gql`
type Query { type Query {
...@@ -10,6 +13,7 @@ const typeDefs = gql` ...@@ -10,6 +13,7 @@ const typeDefs = gql`
username: String username: String
} }
` `
const users = [ const users = [
{ name: 'Leeroy Jenkins', username: 'leeroy' }, { name: 'Leeroy Jenkins', username: 'leeroy' },
{ name: 'Foo Bar', username: 'foobar' }, { name: 'Foo Bar', username: 'foobar' },
...@@ -28,12 +32,8 @@ const resolvers = { ...@@ -28,12 +32,8 @@ const resolvers = {
export const schema = makeExecutableSchema({ typeDefs, resolvers }) export const schema = makeExecutableSchema({ typeDefs, resolvers })
export const config = { const server = new ApolloServer({
api: { schema,
bodyParser: false,
},
}
export default new ApolloServer({ schema }).createHandler({
path: '/api/graphql',
}) })
export default startServerAndCreateNextHandler(server)
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
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