Usage

Learn how to use headers and middleware both globally and per route.


Nuxt Security by default registers a set of global Nuxt routeRules that will make your application more secure by default. Both headers and middleware can be easily configured and even disabled when needed.

ℹ Read more about security headers here.

Global configuration

To override default behavior for Nuxt Security globally, follow this pattern:

export default defineNuxtConfig({  security: {    headers: {      // certain header      xXSSProtection: '1',    },    // certain middleware    rateLimiter: {      // options    }  }})

Per route configuration

To enable per-route configuration, use the routeRules like following:

export default defineNuxtConfig({  routeRules: {    '/custom-route': {      headers: {        // certain header        'Cross-Origin-Embedder-Policy': 'require-corp'      },      // certain middleware      security: {        rateLimiter: {          // options        }      }    }  }})
When using routeRules, make sure to:
  1. use the proper HTTP Header names like Cross-Origin-Embedder-Policy instead of crossOriginEmbedderPolicy and to not set the headers inside security. These headers are handled by Nuxt and you can check more here.
  2. add middleware inside of security in certain route rule. This is a custom NuxtSecurity addition that does not exists in core Nuxt.

You can also use route roules in pages like following:

<template>  <div>Hello from page</div></template><script setup lang="ts">defineRouteRules({  headers: {    'X-XSS-Protection': '1'  },  security: {    rateLimiter: {      tokensPerInterval: 3,      interval: 60000,    },  }})</script>
To enable this macro, add following configuration to your nuxt.config.ts file:
experimental: {  inlineRouteRules: true},

Disabling functionality

To disable certain middleware or headers, follow this pattern:

export default defineNuxtConfig({  // global  security: {    headers: {      // certain header      contentSecurityPolicy: false    },    // certain middleware    rateLimiter: false  },  // per route  routeRules: {    '/custom-route': {      security: {        rateLimiter: false      }    }  }})