@nosecone/next
v1.9.1
Published
Protect your Next.js application with secure headers
Readme
@nosecone/next
Protect your Next.js application with secure headers.
What is this?
This is our adapter to integrate Nosecone into Next.js. Nosecone makes it easy to add and configure security headers. This package exists so that we can provide the best possible experience to Next users.
When should I use this?
You can use this package with or without Arcjet to protect your app if you are
using Next.js.
Use @nosecone/sveltekit if you use Sveltekit and
use nosecone itself if you use a different framework.
Install
This package is ESM only. Install with npm in Node.js:
npm install @nosecone/nextUse
Configure Nosecone in a middleware.ts file:
import { createMiddleware } from "@nosecone/next";
export const config = {
// matcher tells Next.js to run middleware on all routes
matcher: ["/(.*)"],
};
export default createMiddleware();…then use connection from next/server in app/layout.tsx:
+import { connection } from "next/server";
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
+ // Opt-out of static generation for every page so the CSP nonce can be applied
+ await connection()
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
);
}Accessing the nonce
When the Content-Security-Policy is enabled, Nosecone generates a unique
nonce for every request. Next.js applies it to the scripts it renders
automatically, but third-party scripts that don't use the Next.js <Script>
component need the nonce passed in manually. For example,
PostHog requires the nonce in its
init call.
Use the nonce function to read the nonce for the current request from a Server
Component, Route Handler, or anywhere else next/headers is available:
import { nonce } from "@nosecone/next";
export default async function Page() {
const cspNonce = await nonce();
return <script nonce={cspNonce}>{`/* ... */`}</script>;
}The page must be dynamically rendered for the nonce to be available, which is
the same requirement as applying the nonce to Next.js scripts (see the app/layout.tsx
example above). nonce returns undefined if the Content-Security-Policy is
disabled or doesn't contain a nonce.
