Introduction
Next.js allows for utilizing a GraphQL API but its implementation may be less clear based on documentation, tutorials, or other resources found online. Most such resources (using Apollo) will make use of a query string in the component, such as:
const GET_MISSIONS = gql`
query missions {
launchesPast {
mission_name
}
}
`;
function Missions() {
const { loading, error, data } = useQuery(GET_MISSIONS);
}
While this is not incorrect, such an implementation loses the benefits of an IDE which can format, lint, etc the query because it is wrapped in a JavaScript string. Instead, we want to take full advantage of separating GraphQL calls into distinct files such as .graphql
or .gql
as we would .md
for markdown or .json
for JSON content.
Next.js and Webpack
In order to use .graphql
files in Next.js, we have to configure the webpack configuration Next.js provides. In order to do so, create or edit the next.config.js
file at the root level of your Next.js application:
module.exports = {
webpack: (config, options) {
config.module.rules.push({
test: /\.(graphql|gql)/,
exclude: /node_modules/,
loader: "graphql-tag/loader"
});
return config;
}
};
What the code above does is tell the webpack configuration of Next.js to parse .graphql
or .gql
files through the graphql-tag
loader. In order for this to work, install graphql
at the root level of the application.
npm install graphql-tag
Now we can refactor the previous component to make use of the new filetype.
import { missions } from 'queries/mission.graphql';
function Component() {
const { loading, error, data } = useQuery(missions);
}
In our new .graphql
file, we can list each query which are exported and can be used in components.
query missions {
launchesPast {
title
author
}
}
Next.js and TypeScript
If using TypeScript with Next.js, you may find the new import will result in TypeScript warning that no modules or type declarations are found.
Cannot find module 'queries/mission.graphql' or its corresponding type declarations.ts
To resolve this, we will need to create a custom type definition. If you don't already have custom types, create a @types
folder at the root level of your application with a graphql.d.ts
file. In this new file, declare the corresponding module.
declare module '*.graphql'
If using .gql
files, create a gql.d.ts
file with declare module '*.gql'
written inside.
Conclusion
Next.js is a powerful framework that allows for a GraphQL API and harnessing the power of utilizing separate GraphQL files for queries just requires a few changes to configurations as mentioned above. A full working example can be found in the repo richardtorres314/graphql-files.
Top comments (1)
this was really helpful, I've been looking for this configuration everywhere but no one talk about it.
thank you so much richard