Next.js allows you to create API Routes within your application. When deployed to Vercel, these routes are created as Serverless Functions, so they will alway run on the server side.
Using Apollo Server, we are going to setup a serverless GraphQL endpoint. This endpoint can then run any backend code and call other APIs or a database (DynamoDB, SQL…).
We will consider that you have already set up your Next.js project.
First of all, let's install apollo-server-micro
.
npm install apollo-server-micro
This package is a Micro integration for Apollo Server. It is shipped as part of every Apollo Server release, so it is not a third-party package.
Micro is a webserver for microservices. Serverless Functions do not require Micro anymore but they have the same API, so they will be able to talk to Apollo Server with this integration.
Create a new file at pages/api/graphql.js
:
import { ApolloServer, gql } from 'apollo-server-micro';
// This data will be returned by our test endpoint
const products = [
{
id: 1,
name: 'Cookie',
price: 300,
},
{
id: 2,
name: 'Brownie',
price: 350,
},
];
// Construct a schema using GraphQL schema language
const typeDefs = gql`
type Product {
id: Int
name: String
price: Int
}
type Query {
products: [Product]
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
products: () => {
return products;
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
export default server.createHandler({
path: '/api/graphql',
});
export const config = {
api: {
bodyParser: false,
},
};
Here is what is happening here:
ApolloServer
instance (imported from the apollo-server-micro
package). This instance has a createHandler
method which generates exactly what a Next.js API route needs, so we just export it. The path
parameter is mandatory and tells the server where it is running. If you want to call your route differently, you can rename this file like any other page and update this parameter.And that's all! You can now query your API by calling the /api/graphql
endpoint.
In development mode, the GraphQL Playground can be reached by opening http://localhost:3000/api/graphql in your browser!