@komw/next-safe-middleware

Strict Content-Security-Policy (CSP) for Next.js with composable middleware

Works for hybrid apps and supports pages with any data fetching method.

Always sets CSP by HTTP Response header and enables easy setup of reporting.

Version

Downloads

MIT

Release

Star on GitHub

Watch on GitHub

Forks on GitHub

Original project

Initially, the project was being developed in the repository https://github.com/nibtime/next-safe-middleware. However, it was likely abandoned by the author (no responses to pull requests, comments, or reported bugs). The lack of support and assistance in merging pull requests and building the target library prompted me to move everything to my own repository. (Szymon Gล‚adysz)

What

This package strives to make the setup and deployment of a strict Content Security Policy (CSP) with Next.js an easy task. The design approach that makes this possible requires Next.js Middleware, which has been introduced as Beta in Next.js 12 and is stable since Next.js 12.2.

This package handles all Strict CSP conundrums for you and works for:

This package always sets CSP as HTTP response header. That enables violation reporting and report-only mode even for static pages. Plus, it provides a middleware and API handlers that make the setup of CSP violation reporting very easy.

Why

Configuring and maintaining a Content-Security-Policy (CSP) can be a tedious and error prone task. Furthermore, classic CSPs with a whitelist approach don't give you the security you might think you get from them, because in a lot of cases, they are automatically bypassable.

There is a much better option: a Hash-based/Nonce-based Strict CSP.

Such CSPs provide much better security and have always the same structure, so they don't need the maintenance that whitelist CSPs need, once they've been set up properly. But this setup is usually a a very big issue with Next.js (and with all web frameworks in general).

This is where this package comes in: To make this setup easy, convenient and a lot less error-prone.

Good Resources about (Strict) Content-Security-Policy (CSP)

TypeScript and JSDoc

This package is written with 100% TypeScript and provides typings for full IntelliSense with CSP and middleware configuration. The typing for CSP directives is borrowed from the CSP integration of SvelteKit.

Furthermore, most middlewares, functions, parameters and types have JSDoc on them, with examples, explanations and links to related resources.

Contributors

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome! Check out the contributing guide for getting started!