Created
September 2, 2022 00:18
-
-
Save tatsuyasusukida/6d0c65b76cffbaedf55619e4c2da6a31 to your computer and use it in GitHub Desktop.
Next.js Apollo Server using apollo-server-micro@3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import '../styles/globals.css' | |
import type { AppProps } from 'next/app' | |
import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client' | |
const client = new ApolloClient({ | |
uri: '/api/graphql', | |
cache: new InMemoryCache(), | |
}) | |
function MyApp({ Component, pageProps }: AppProps) { | |
return ( | |
<ApolloProvider client={client}> | |
<Component {...pageProps} /> | |
</ApolloProvider> | |
) | |
} | |
export default MyApp |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { gql, useQuery } from "@apollo/client"; | |
import { NextPage } from "next"; | |
const SAY_HELLO = gql` | |
query SayHello { | |
sayHello | |
} | |
` | |
const Client: NextPage = () => { | |
const {data} = useQuery(SAY_HELLO) | |
return ( | |
<main> | |
{JSON.stringify(data)} | |
</main> | |
) | |
} | |
export default Client |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ApolloServer, gql } from 'apollo-server-micro' | |
import type { NextApiRequest, NextApiResponse, PageConfig } from 'next' | |
const typeDefs = gql` | |
type Query { | |
sayHello: String | |
} | |
` | |
const resolvers = { | |
Query: { | |
sayHello() { | |
return 'Hello World!' | |
}, | |
}, | |
} | |
const apolloServer = new ApolloServer({ typeDefs, resolvers }) | |
const handler = apolloServer.start() | |
.then(() => apolloServer.createHandler({ path: '/api/graphql' })) | |
export default async function (req: NextApiRequest, res: NextApiResponse) { | |
if (process.env.NODE_ENV === 'development') { | |
res.setHeader('Access-Control-Allow-Origin', '*') | |
res.setHeader('Access-Control-Allow-Headers', 'Content-Type') | |
if (req.method === 'OPTIONS') { | |
res.status(200).end() | |
return | |
} | |
} | |
await (await handler)(req, res) | |
} | |
export const config: PageConfig = { | |
api: { | |
bodyParser: false, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment