Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 25, 2021 12:28 pm GMT

TIL: How to set security headers for Gatsby Develop

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.jsconst { createProxyMiddleware } = require("http-proxy-middleware")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.jsmodule.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.jsmodule.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


Original Link: https://dev.to/khenhey/til-how-to-set-security-headers-for-gatsby-develop-4kj9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To