GraphQL Yoga v4 documentation (superseded by v5): Express is the most popular web framework for Node.js. It is a minimalist framework that provides a robust set of features to handle HTTP on Node.js applications.
Express is the most popular web framework for Node.js. It is a minimalist
framework that provides a robust set of features to handle HTTP on Node.js applications. You can
easily integrate GraphQL Yoga into your Express application with a few lines of code.
Installation
npm i express graphql-yoga graphql
yarn add express graphql-yoga graphql
pnpm add express graphql-yoga graphql
bun add express graphql-yoga graphql
Example
import express from 'express'import { createYoga } from 'graphql-yoga'const app = express()const yoga = createYoga()// Bind GraphQL Yoga to the graphql endpoint to avoid rendering the playground on any pathapp.use(yoga.graphqlEndpoint, yoga)app.listen(4000, () => { console.log('Running a GraphQL API server at http://localhost:4000/graphql')})
You can also check a full example on our GitHub repository
here
To avoid applying this configuration to other endpoints you may have on your Express server, you can
use Express.Router to create a new router instance and apply the configuration only to the GraphQL
Yoga endpoint.
import express from 'express'import helmet from 'helmet'const app = express()const yoga = createYoga()const yogaRouter = express.Router()// GraphiQL specefic CSP configurationyogaRouter.use( helmet({ contentSecurityPolicy: { directives: { 'style-src': ["'self'", 'unpkg.com'], 'script-src': ["'self'", 'unpkg.com', "'unsafe-inline'"], 'img-src': ["'self'", 'raw.githubusercontent.com'] } } }))yogaRouter.use(yoga)// By adding the GraphQL Yoga router before the global helmet middleware,// you can be sure that the global CSP configuration will not be applied to the GraphQL Yoga endpointapp.use(yoga.graphqlEndpoint, yogaRouter)// Add the global CSP configuration for the rest of your server.app.use(helmet())// You can know register your other endpoints that will not be affected by the GraphiQL CSP configurationapp.get('/hello', (req, res) => { res.send('Hello World!')})app.listen(4000, () => { console.log('Running a GraphQL API server at http://localhost:4000/graphql')})
You can also check a full example on our GitHub repository
here
This site uses cookies for analytics and improving your experience.