Photo by Henry & Co on Unsplash
There might come a time that you want to run your Gatsby app with security headers in development. To do this, you can utilize advanced proxying. Gatsby has a way to expose the Express.js development server it uses to run the app whenever you use gatsby develop
. This way you can add Express middleware.
TL;DR
If you just want to get your solution, feel free to use this setup inside your gatsby-config.js
to set any security header you want. This example shows how you could set the X-Frame-Options
HTTP response header to DENY.
// gatsby-config.js
module.exports = {
developMiddleware: app => {
app.use((req, res, next) => {
res.set('X-Frame-Options', 'DENY');
next();
});
},
}
Let's break it down
First we make sure we actually have a gatsby-config.js
file. This file should be in the root of your Gatsby project and it can contain a bunch of different information. If you want to know more about this file, check out Gatsby's own docs.
// gatsby-config.js
module.exports = {
// an empty config file!
}
Using developMiddleware
To expose Express.js we use the configuration key called developMiddleware
. We pass it a function that takes a parameter called app
. We can use that to add middleware to Express.js.
We use app.use()
and pass it a function that takes req, res, next
parameters. Inside the function we set our security header on the res
(response) object. After this, we call the next function that we got as a parameter.
// gatsby-config.js
module.exports = {
developMiddleware: app => {
app.use((req, res, next) => {
res.set('X-Frame-Options', 'DENY');
next();
});
},
}
Done! You should now be able to run gatsby develop
and see the proper security headers on the documents that it serves you. Make sure to restart your server if you already had it running though, otherwise the changes won't come through.
Originally posted on my website
Top comments (5)
Good post! 😉
Do you usually use Express with Gatsby? What do you usually use it for?
Cheers 👋
In this case Gatsby itself exposes Express for people to use in development. For example for proxying. If you want to read more about that I can recommend Gatsby’s own docs.
I thought you used it for production, and I did not understand exactly how it works 😅
I check it out. Thanks 😉🙏
There might be use cases :) this one is specifically for using it within development :)
You are an expert developer, I have a lot to learn from you 😉 I will closely follow your posts. I just published my personal website developed with gatsby, but I have a lot to learn Karin 😅