Nuxt Unscrf

🚀 Features
- ⛰ Nuxt 4.7+ and Nitro 3 ready
- 👌 Zero config: Configuration for common use cases
- ⚡ Nitro ready: Customizable nitro storage.
- ⚙️ Auto import: Provide auto import functions.
- 🦾 Type strong: Written in typescript
📦 Install
npm i @xarenas107/nuxt-uncsrf -D
🦄 Usage
Add @xarenas107/nuxt-uncsrf to the modules section of nuxt.config.ts.
export default defineNuxtConfig({
modules: [
'@xarenas107/nuxt-uncsrf'
]
})
By default csrf protection is applied only for routes /api. All methods are protected, including GET, HEAD and OPTIONS. If you need more control, use nitro route rules.
Each browser gets a random identifier, stored encrypted in the x-csrf-token cookie when a page is rendered. Requests without a valid token are rejected with a 403. Set NUXT_UNCSRF_SECRET or uncsrf.secret to your own secret.
Use false to disable protection
routeRules:{
'/locale/**': {
uncsrf: false,
}
}
Protect other routes, or only some methods
routeRules:{
'/form': {
uncsrf: {},
},
'/api/**': {
uncsrf: { methods: ['POST', 'PUT', 'PATCH', 'DELETE'] },
}
}
You can customize storage
// define storage on `nuxt.config.ts`
export default defineNuxtConfig({
uncsrf:{
storage:{
driver:'memory'
}
}
})
Or use a previously defined storage'
export default defineNuxtConfig({
nitro:{
kv:{
'security':{
driver:'memory',
}
}
},
uncsrf:{
storage:'security'
}
})
That's it! You can now use @xarenas107/nuxt-uncsrf in your Nuxt app ✨
Limitations
- The token is only read from the cookie, so protection relies on
SameSite=Strict. It does not cover attacks from sibling subdomains.
- Prerendered and cached pages (
cache, swr, isr) do not issue tokens. useCsrf() gets one from the /_uncsrf endpoint on the client, so with endpoint: false a dynamic page has to be visited first.
- CORS preflight requests carry no cookies, so
OPTIONS is rejected unless excluded with methods.
- An expired token is renewed once. Other requests sent at the same time with it can be rejected.
- Identifiers that are no longer used are not removed from storage automatically.
⬆️ Migrating from v2
- Nuxt 4.7+ and Nitro 3 are required. Nuxt 3 is no longer supported.
- Tokens are issued per client, not per IP. Tokens issued by v2 are no longer valid, so clients get a new one on their next visit.
- Only
/api routes are protected by default. v2 protected every route except /_nuxt and /__nuxt for GET. Use routeRules with uncsrf: {} to protect other routes.
- The cookie is
httpOnly. It can no longer be read from client code, use useCsrf() instead.
useCsrf() returns { token, refresh } instead of { csrf }. token is a ref, and refresh() fetches the token from the /_uncsrf endpoint.
- const { csrf } = useCsrf()
+ const { token } = useCsrf()
- A previously defined storage is declared in
nitro.kv, not in nitro.storage.