-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(example): Add Nosecone example with custom router #2662
Open
davidmytton
wants to merge
1
commit into
main
Choose a base branch
from
david/nosecone-router
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
<a href="https://arcjet.com" target="_arcjet-home"> | ||
<picture> | ||
<source media="(prefers-color-scheme: dark)" srcset="https://arcjet.com/logo/arcjet-dark-lockup-voyage-horizontal.svg"> | ||
<img src="https://arcjet.com/logo/arcjet-light-lockup-voyage-horizontal.svg" alt="Arcjet Logo" height="128" width="auto"> | ||
</picture> | ||
</a> | ||
|
||
# Nosecone + Next.js with custom middleware router | ||
|
||
This example shows how to use | ||
[Nosecone](https://docs.arcjet.com/nosecone/quick-start) with Next.js and a | ||
custom middleware router to configure multiple middlewares for different routes. | ||
|
||
## How to use | ||
|
||
1. From the root of the project, install the SDK dependencies. | ||
|
||
```bash | ||
npm ci | ||
``` | ||
|
||
2. Enter this directory and install the example's dependencies. | ||
|
||
```bash | ||
cd examples/nosecone-nextjs-router | ||
npm ci | ||
``` | ||
|
||
3. Start the dev server. | ||
|
||
```bash | ||
npm run dev | ||
``` | ||
|
||
4. Visit `http://localhost:3000/` | ||
|
||
5. Check the response headers to see the default Nosecone security headers. |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
@tailwind base; | ||
@tailwind components; | ||
@tailwind utilities; | ||
|
||
:root { | ||
--background: #ffffff; | ||
--foreground: #171717; | ||
} | ||
|
||
@media (prefers-color-scheme: dark) { | ||
:root { | ||
--background: #0a0a0a; | ||
--foreground: #ededed; | ||
} | ||
} | ||
|
||
body { | ||
color: var(--foreground); | ||
background: var(--background); | ||
font-family: Arial, Helvetica, sans-serif; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import type { Metadata } from "next"; | ||
import { Geist, Geist_Mono } from "next/font/google"; | ||
import "./globals.css"; | ||
|
||
const geistSans = Geist({ | ||
variable: "--font-geist-sans", | ||
subsets: ["latin"], | ||
}); | ||
|
||
const geistMono = Geist_Mono({ | ||
variable: "--font-geist-mono", | ||
subsets: ["latin"], | ||
}); | ||
|
||
export const metadata: Metadata = { | ||
title: "Create Next App", | ||
description: "Generated by create next app", | ||
}; | ||
|
||
export default function RootLayout({ | ||
children, | ||
}: Readonly<{ | ||
children: React.ReactNode; | ||
}>) { | ||
return ( | ||
<html lang="en"> | ||
<body | ||
className={`${geistSans.variable} ${geistMono.variable} antialiased`} | ||
> | ||
{children} | ||
</body> | ||
</html> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
import Image from "next/image"; | ||
|
||
export default function Home() { | ||
return ( | ||
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> | ||
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start"> | ||
<Image | ||
className="dark:invert" | ||
src="/next.svg" | ||
alt="Next.js logo" | ||
width={180} | ||
height={38} | ||
priority | ||
/> | ||
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]"> | ||
<li className="mb-2"> | ||
Get started by editing{" "} | ||
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold"> | ||
app/page.tsx | ||
</code> | ||
. | ||
</li> | ||
<li>Save and see your changes instantly.</li> | ||
</ol> | ||
|
||
<div className="flex gap-4 items-center flex-col sm:flex-row"> | ||
<a | ||
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5" | ||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" | ||
target="_blank" | ||
rel="noopener noreferrer" | ||
> | ||
<Image | ||
className="dark:invert" | ||
src="/vercel.svg" | ||
alt="Vercel logomark" | ||
width={20} | ||
height={20} | ||
/> | ||
Deploy now | ||
</a> | ||
<a | ||
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44" | ||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" | ||
target="_blank" | ||
rel="noopener noreferrer" | ||
> | ||
Read our docs | ||
</a> | ||
</div> | ||
</main> | ||
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center"> | ||
<a | ||
className="flex items-center gap-2 hover:underline hover:underline-offset-4" | ||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" | ||
target="_blank" | ||
rel="noopener noreferrer" | ||
> | ||
<Image | ||
aria-hidden | ||
src="/file.svg" | ||
alt="File icon" | ||
width={16} | ||
height={16} | ||
/> | ||
Learn | ||
</a> | ||
<a | ||
className="flex items-center gap-2 hover:underline hover:underline-offset-4" | ||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" | ||
target="_blank" | ||
rel="noopener noreferrer" | ||
> | ||
<Image | ||
aria-hidden | ||
src="/window.svg" | ||
alt="Window icon" | ||
width={16} | ||
height={16} | ||
/> | ||
Examples | ||
</a> | ||
<a | ||
className="flex items-center gap-2 hover:underline hover:underline-offset-4" | ||
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" | ||
target="_blank" | ||
rel="noopener noreferrer" | ||
> | ||
<Image | ||
aria-hidden | ||
src="/globe.svg" | ||
alt="Globe icon" | ||
width={16} | ||
height={16} | ||
/> | ||
Go to nextjs.org → | ||
</a> | ||
</footer> | ||
</div> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import { type NoseconeOptions, defaults, createMiddleware as noseconeMiddleware } from "@nosecone/next"; | ||
import { | ||
type NextFetchEvent, | ||
type NextMiddleware, | ||
type NextRequest, | ||
NextResponse, | ||
} from "next/server"; | ||
import { match } from "path-to-regexp"; | ||
|
||
// Next.js middleware config | ||
export const config = { | ||
matcher: ['/((?!_next/|_static|_vercel|[\\w-]+\\.\\w+).*)'], | ||
}; | ||
|
||
// Nosecone security headers configuration | ||
// https://docs.arcjet.com/nosecone/quick-start | ||
const noseconeOptions: NoseconeOptions = { | ||
...defaults, | ||
// Customize security headers here | ||
// See https://docs.arcjet.com/nosecone/reference | ||
}; | ||
const securityHeaders = noseconeMiddleware(noseconeOptions); | ||
|
||
// Add any paths you want to run different middleware for. They use | ||
// path-to-regexp which is the same as the Next.js config. You can provide a | ||
// single middleware or an array of middlewares. | ||
export default router({ | ||
// Run nosecone middleware on any path | ||
"/{*path}": [securityHeaders] | ||
}); | ||
|
||
// A simple middleware router that allows you to run different middleware based | ||
// on the path of the request. | ||
function router( | ||
pathMiddlewareMap: Record<string, NextMiddleware | NextMiddleware[]>, | ||
): NextMiddleware { | ||
const middleware = Object.entries(pathMiddlewareMap).map( | ||
([path, middleware]) => { | ||
if (Array.isArray(middleware)) { | ||
return [match(path), middleware] as const; | ||
} else { | ||
return [match(path), [middleware]] as const; | ||
} | ||
}, | ||
); | ||
|
||
return async ( | ||
request: NextRequest, | ||
event: NextFetchEvent, | ||
): Promise<NextResponse | Response> => { | ||
const path = request.nextUrl.pathname || "/"; | ||
const addedHeaders = new Headers(); | ||
|
||
for (const [matchFunc, middlewareFuncs] of middleware) { | ||
const m = matchFunc(path); | ||
if (m) { | ||
for (const fn of middlewareFuncs) { | ||
const resp = await fn(request, event); | ||
// TODO: better response guards | ||
if (typeof resp !== "undefined" && resp !== null) { | ||
resp.headers.forEach((value, key) => { | ||
addedHeaders.set(key, value); | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
|
||
addedHeaders.set("x-middleware-next", "1"); | ||
|
||
return new Response(null, { | ||
headers: addedHeaders, | ||
}); | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
/// <reference types="next" /> | ||
/// <reference types="next/image-types/global" /> | ||
|
||
// NOTE: This file should not be edited | ||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import type { NextConfig } from "next"; | ||
|
||
const nextConfig: NextConfig = { | ||
/* config options here */ | ||
}; | ||
|
||
export default nextConfig; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@blaine-arcjet could you review my fix in #2639 (comment) please? Seems like we should handle redirects and auth errors by just returning the response, but that might leave the security headers unset.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there a reason we can't add the headers to returned response before returning it from the middleware?
It looks like the implementation for
NextResponse.redirect()
isn't complex:So we could return a
Response
instantly that sets the status code & Location header.Also, to make this resilient, we probably want to handle
NextResponse.rewrite()
, which looks like it sets a different header thanNextResponse.next()
:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ideally we'd add the headers to all responses. So this is really about extending how we handle the redirect and rewrites to make sure they're captured correctly.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@blaine-arcjet could you add this to the code when you get a chance please? You'll do a better job than me at this!