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)
$ npm install next-proxy-managerCreate 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).*)',
],
};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
}Some examples to get you started...
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;
}export function proxy(req) {
const response = this.NextResponse.next();
response.headers.set('x-demo-token', 'abc123');
return response;
}export function proxy(req) {
const response = this.NextResponse.next();
response.cookies.set('demo-cookie', 'foo');
return response;
}export function proxy(req) {
req.headers.set('user-agent', 'Mobile iOS 17.4.1 (normalized)');
return;
}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();
}export async function proxy(req) {
await fetch('http://analytics.com/hit', {
method: 'POST',
body: JSON.stringify({
utm: req.nextUrl.searchParams.get('utm'),
}),
});
}export function proxy(req) {
if (authorized) {
return this.NextResponse.next();
}
return this.NextResponse.json({ response: 'auth failed' }, { status: 401 });
}export function proxy(req) {
return this.NextResponse.redirect(new URL('/alternate/path', req.url));
}export function proxy(req) {
return this.NextResponse.rewrite(new URL('/alternate/path', req.url));
}