By default, the Next.JS bootstrap comes equipped with GraphQL for an automated API experience.
Want to disable GraphQL add the following to your config:
{
"graphql": {
"enabled": false
}
}
Additional GraphQL Documentation: https://graphql.org/learn/
The GraphQL api will be running on the following URL:
/api
Please note: You need to do a POST to access the API part.
If you directly visit this URL (GET Request) you will access the GraphQL Playground.
This can be used to see the documentation for all query's and run sample queries.
Additional GraphQL Playground Documentation: https://github.com/graphql/graphql-playground
The GraphQL api will be running on the following URL:
/api/mock
Please note: You need to do a POST to access the API part.
To add your own GraphQL Compose field to the bootstrap use this included function:
const bootstrap = new NextBootstrap(__dirname, process.cwd(), nextConfig);
bootstrap.addGraphQLField({
dummy: {
name: 'dummy',
type: '[String]',
resolve: () => {
return [
"A string",
"Another string"
];
}
}
});
bootstrap.init();
Additional GraphQL Compose Documentation: https://graphql-compose.github.io/docs/intro/quick-start.html
To protect Mongo collections in GraphQL query's you can use the following example code to protect a specific collection:
In this example we want to protect the Page
collection:
const dset = require('dset');
const jwt = require('jsonwebtoken');
const bootstrap = new NextBootstrap(__dirname, process.cwd(), nextConfig);
bootstrap.config.graphql.protectedCollections.Page = (req, next) => {
let check = {};
// Verify if the JWT Token send via the GraphQL Connection is valid (GraphQL is looking to a jwt header)
try {
check = jwt.verify(req.context.authentication, bootstrap.config.user.secret);
} catch (e) {
return new Error('Incorrect/expired token!');
}
// Check if the JWT contains a valid username
if(check.username) {
// Force the query to only return items that a user owns
dset(req, 'args.filter.user', check.username);
} else {
return new Error('Invalid token data!');
}
// Let GraphQL Execute the query
return next();
};
bootstrap.init();
Additional GraphQL Compose Documentation: https://graphql-compose.github.io/docs/basics/what-is-resolver.html#how-resolverwrapresolve-work-internally
Last modified | Friday, April 30, 2021, 12:00:21 PM UTC |
Last author | Colin van Eenige |
Commit ID | 4c7a701 |