Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ This is not Koa and not Express, this is a package for next.js, in its unique st
- [Base example](https://github.com/alexdln/nimpl-proxy-chain/tree/main/examples/base).
- [next-auth + next-intl example](https://github.com/alexdln/nimpl-proxy-chain/tree/main/examples/auth-intl).
- [next-auth5 + next-intl example](https://github.com/alexdln/nimpl-proxy-chain/tree/main/examples/auth5-intl).
- [Custom auth](https://github.com/alexdln/nimpl-proxy-chain/tree/main/examples/basic-auth).

## Development

Expand Down
1 change: 1 addition & 0 deletions examples/basic-auth/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
BASIC_AUTH="login:password"
37 changes: 37 additions & 0 deletions examples/basic-auth/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
pnpm-lock.yaml

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
36 changes: 36 additions & 0 deletions examples/basic-auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
4 changes: 4 additions & 0 deletions examples/basic-auth/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};

export default nextConfig;
22 changes: 22 additions & 0 deletions examples/basic-auth/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "examples-basic-auth",
"version": "1.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "NODE_ENV=production next build",
"start": "next start"
},
"dependencies": {
"@nimpl/proxy-chain": "workspace:*",
"next": "16.1.1",
"react": "19.2.3",
"react-dom": "19.2.3"
},
"devDependencies": {
"@types/node": "25.0.3",
"@types/react": "19.2.7",
"@types/react-dom": "19.2.3",
"typescript": "5.9.3"
}
}
1 change: 1 addition & 0 deletions examples/basic-auth/public/next.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/basic-auth/public/vercel.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/basic-auth/src/app/favicon.ico
Binary file not shown.
16 changes: 16 additions & 0 deletions examples/basic-auth/src/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}

html,
body {
max-width: 100vw;
overflow-x: hidden;
}

a {
color: inherit;
text-decoration: none;
}
20 changes: 20 additions & 0 deletions examples/basic-auth/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { type Metadata } from "next/types";

import "./globals.css";

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>{children}</body>
</html>
);
}
7 changes: 7 additions & 0 deletions examples/basic-auth/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function Home() {
return (
<div>
<p>Home page</p>
</div>
);
}
58 changes: 58 additions & 0 deletions examples/basic-auth/src/basicAuthMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from "next/server";

const BASIC_AUTH_COOKIE_NAME = "__basic_auth";
const COOKIE_MAX_AGE = 60 * 60 * 24 * 14; // 14 days

function createAuthHash(username: string, password: string): string {
return Buffer.from(`${username}:${password}`).toString("base64");
}

export const basicAuthMiddleware = async (request: NextRequest) => {
if (!process.env.BASIC_AUTH) {
return;
}

const basicAuthParts = process.env.BASIC_AUTH.split(":");
if (basicAuthParts.length !== 2 || !basicAuthParts[0] || !basicAuthParts[1]) {
console.error('Server misconfiguration: BASIC_AUTH must be in "username:password" format');
return new Response("Server misconfiguration", {
status: 500,
});
}
const [username, password] = basicAuthParts;
const expectedAuthHash = createAuthHash(username, password);

// Fast path: check cookie first (covers all subsequent requests including RSC/prefetch)
const authCookie = request.cookies.get(BASIC_AUTH_COOKIE_NAME);
if (authCookie?.value === expectedAuthHash) {
return;
}

const authHeader = request.headers.get("authorization");
if (authHeader) {
const base64Credentials = authHeader.split(" ")[1];
if (base64Credentials) {
const credentials = Buffer.from(base64Credentials, "base64").toString("ascii");
const [inputUsername, inputPassword] = credentials.split(":");

if (inputUsername === username && inputPassword === password) {
// Set the auth cookie for subsequent requests and proceed to the next proxy handler
const nextResponse = NextResponse.next();
nextResponse.cookies.set(BASIC_AUTH_COOKIE_NAME, expectedAuthHash, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: COOKIE_MAX_AGE,
path: "/",
});
return nextResponse;
}
}
}
return new Response("Authentication required", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Auth"',
},
});
};
23 changes: 23 additions & 0 deletions examples/basic-auth/src/proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { chain } from "@nimpl/proxy-chain";
import { basicAuthMiddleware } from "./basicAuthMiddleware";
import { NextResponse } from "next/server";

export default chain([
basicAuthMiddleware,
async (request) => {
const next = NextResponse.next({
headers: new Headers({ "x-client-header-set-by-middleware": "true" }),
request: { headers: new Headers({ "x-request-pathname": request.nextUrl.pathname }) },
});
next.cookies.set("test", "cookie", { maxAge: 1000 * 60 * 60 * 24 * 30 });

return next;
},
(req) => {
console.log("Request summary", req.summary);
},
]);

export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|.well-known).*)"],
};
41 changes: 41 additions & 0 deletions examples/basic-auth/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./src/*"
]
},
"target": "ES2017"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
"prepare": "husky"
},
"lint-staged": {
"*.{ts,tsx,js,jsx}": ["eslint"]
"*.{ts,tsx,js,jsx}": [
"eslint"
]
},
"repository": {
"type": "git",
Expand All @@ -31,8 +33,9 @@
"resolutions": {
"examples-auth-intl>@nimpl/proxy-chain": "workspace:*",
"examples-auth5-intl>@nimpl/proxy-chain": "workspace:*",
"examples-base>@nimpl/proxy-chain": "workspace:*"
"examples-base>@nimpl/proxy-chain": "workspace:*",
"examples-basic-auth>@nimpl/proxy-chain": "workspace:*"
},
"license": "MIT",
"packageManager": "pnpm@9.7.0+sha512.dc09430156b427f5ecfc79888899e1c39d2d690f004be70e05230b72cb173d96839587545d09429b55ac3c429c801b4dc3c0e002f653830a420fa2dd4e3cf9cf"
}
}
11 changes: 10 additions & 1 deletion package/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@
"name": "@nimpl/proxy-chain",
"version": "1.0.0",
"description": "Create a chain of native Next.js proxies seamlessly, without changing any existing proxy code",
"type": "module",
"main": "./dist/chain.js",
"types": "./dist/chain.d.ts",
"exports": {
".": {
"types": "./dist/chain.d.ts",
"import": "./dist/chain.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsc"
"build": "tsup"
},
"keywords": [
"next",
Expand All @@ -33,6 +41,7 @@
"license": "MIT",
"devDependencies": {
"next": "16.1.1",
"tsup": "8.5.1",
"typescript": "5.9.3"
},
"peerDependencies": {
Expand Down
1 change: 1 addition & 0 deletions package/src/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const chain =
event,
middlewares,
logger,
config?.breakOnTypes,
);
const next = formatResponse(summary);

Expand Down
Loading