next-proxy-manager
v1.1.0
Published
A better Proxy Manager for Next.js
Downloads
4
Readme
next-proxy-manager
A better Proxy Manager for Next.js
- Modularize and extract functions into separate files
- Includes ALL proxy/middleware functionality in each module (headers, cookies, redirects, async actions, and more)
Install
$ npm install next-proxy-managerSet-up the Proxy Entry Point
Create a proxy.js file in the root of your project (see Next.js File Conventions) and import as many proxy modules as you want. Modules will be executed in the order that you place them into the array.
import nextProxyManager from 'next-proxy-manager';
import * as authProxy from './my-proxy-middleware/auth.js';
import * as redirectProxy from './my-proxy-middleware/redirect.js';
import * as loggerProxy from './my-proxy-middleware/logger.js';
export const proxy = nextProxyManager([
authProxy,
redirectProxy,
loggerProxy,
]);
// Optionally add matchers here if you want them to affect ALL proxy middleware
export const config = {
matcher: [
'/((?!_next|favicon.ico).*)',
],
};Create Your Proxy Modules
Each module should follow all of the same rules and behaviors as specified in the Next.js Proxy Documentation
All proxy modules should export a proxy function and an optional config object.
The proxy function takes a NextRequest instance and should return a NextResponse instance or undefined. For convenience you can use this.NextResponse to create a response instance.
export const config = { // Optional
matcher: ['/api/*path'],
};
/**
* @param {NextRequest} request
* @param {NextFetchEvent} event
* @returns {Promise<NextResponse>}
*/
export function proxy(request, event) {
return this.NextResponse.next(); // Do nothing, just continue to next handler
// Alternatively, just return undefined. This results in the same behavior
}Examples
Some examples to get you started...
Read request data
export const config = {
matcher: ['/api/users/:id/*path'],
};
export function proxy(req) {
console.log(req.method); // GET
console.log(req.mode); // cors
console.log(req.cache); // default
console.log(req.credentials); // same-origin
console.log(req.referrer); // about:client
console.log(req.url); // http://localhost:3000/api/users/123/account/upgrade?utm=campaign
console.log(req.nextUrl.hostname); // localhost
console.log(req.nextUrl.pathname); // /api/users/123/account/upgrade
console.log(req.nextUrl.searchParams.get('utm')); // campaign
console.log(req.headers.get('user-agent')); // Mozilla/5.0 ...
console.log(req.cookies.get('token')); // { name: 'token', value: '98765' }
console.log(req.params); // { id: '123', path: ['account', 'upgrade'] }
return;
}Set a response header
export function proxy(req) {
const response = this.NextResponse.next();
response.headers.set('x-demo-token', 'abc123');
return response;
}Set a response cookie
export function proxy(req) {
const response = this.NextResponse.next();
response.cookies.set('demo-cookie', 'foo');
return response;
}Override a request header
export function proxy(req) {
req.headers.set('user-agent', 'Mobile iOS 17.4.1 (normalized)');
return;
}Override a request cookie
export function proxy(req) {
const cookieToken = req.cookies.get('token') || {};
if (cookieToken.value === '98765') {
req.cookies.delete('token');
req.cookies.set('token-valid', 'ok');
}
return this.NextResponse.next();
}Log to external analytics and continue
export async function proxy(req) {
await fetch('http://analytics.com/hit', {
method: 'POST',
body: JSON.stringify({
utm: req.nextUrl.searchParams.get('utm'),
}),
});
}Send a simple JSON Response
export function proxy(req) {
if (authorized) {
return this.NextResponse.next();
}
return this.NextResponse.json({ response: 'auth failed' }, { status: 401 });
}Redirect a request to a different path
export function proxy(req) {
return this.NextResponse.redirect(new URL('/alternate/path', req.url));
}Rewrite a request to show different content
export function proxy(req) {
return this.NextResponse.rewrite(new URL('/alternate/path', req.url));
}