graphql-yoga and helmet #2891
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi, Here is an example that worked for me: app.use(
helmet({
contentSecurityPolicy: {
directives: {
'style-src': ["'self'", 'unpkg.com'],
'script-src': ["'self'", 'unpkg.com', "'unsafe-inline'"],
'img-src': ["'self'", 'raw.githubusercontent.com']
}
}
})
) If you want this configuration to be enabled only for the graphiql route (to avoid enabling import express from 'express'
import helmet from 'helmet'
const app = express()
const yoga = createYoga()
const yogaRouter = express.Router()
// GraphiQL specefic CSP configuration
yogaRouter.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 endpoint
app.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 configuration
app.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 find a working example of this configuration in this not yet merged PR: #2902 |
Beta Was this translation helpful? Give feedback.
Hi,
Since the GraphiQL page is actually loaded from
unpkg.com
, you need to configure helmet to allow execution of scripts from this source. You will also need to allow inline scripts execution since GraphiQL is bundled using Webpack, which rely on injection of script tags at runtime.Here is an example that worked for me:
If you want this configuration to be enabled only for the graphiql route (to avoid enabling
unsafe-inline
everyw…