'How to setup specific headers in Nuxt?

I am currently trying to setup specific response header attributes such as X-Frame-Options, X-Content-Type-Options, Cache-Control, and Set-Cookie SameSite on my Nuxt project. Is there an easy way to explicitly declare those headers in nuxt.config.js file ?

I know external modules such as Helmet exists for that specific purpose but I can't believe there is nothing built-in I can use for this right ?



Solution 1:[1]

You can use a server middleware for this, create an headers.js (can have any name) file with the code bellow

import express from 'express';

const app = express();

app.use((req, res, next) => {
    
    res.set({
        "X-Frame-Options": "SAMEORIGIN",
        "X-XSS-Protection": "1; mode=block",
        "X-Content-Type-Options": "nosniff"
    });
    //or
    res.set("Content-Security-Policy", "upgrade-insecure-requests; block-all-mixed-content;");
    //or
    res.header("Referrer-Policy", "strict-origin-when-cross-origin");
    res.header("Feature-Policy", "camera 'none'; microphone 'none'");
    res.header("Permissions-Policy", "camera=(), microphone=()");

    next();
});

export default app;

If you are using Nuxt3, you can just create a headers.js file in server/middleware directory, for Nuxt2 you will need to specify it in nuxt.config.js

export default {
  serverMiddleware: [
    { path: '/server-middleware', handler: '~/server-middleware/headers.js' }
  ]
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rjcpereira