How to pass data from back-end middleware to backend route, handled by the middleware?
Unanswered
Sun bear posted this in #help-forum
Sun bearOP
Best way to do this without just repeating myself for every route?
9 Replies
Sun bearOP
Trying to achieve the same type of thing you would in Expressjs with middleware then setting like
req.user = userThis is basically the Express equivalent of what I want to do:
app.use((req, res, next) => {
const token = req.cookies.token;
const user = /* Code to fetch user from DB */;
req.user = user;
next();
});Using NextJS 14 with the app router btw ^^
heya you can use a custom header for that
// @file middleware.ts
export default async function middleware(
req: NextRequest
): Promise<NextResponse> {
// do some stuff
const username = "...";
// suppose i want to pass username to the pages
const headers = new Headers(req.headers);
headers.append("X-Middleware-Username", username);
return NextResponse.next({ request: { headers } });
}
// @file /app/page.tsx
export default function Page() {
const username = headers().get("X-Middleware-Username")!;
return <p>Welcome aboard, {username}!</p>
}the header name can be whatever you wanted, it's standard to use
X-... for "internal" headers. for me i'd use a different file to store it to make it "dry-er"// @file utils/headers.ts
export const MIDDLEWARE_USERNAME_HEADER = "X-Middleware-Username";will that still work
yeah it should work
Northeast Congo Lion
The custom header is the only way I've found to do it, because the middleware and the backend are separate processes.