Next.js Discord

Discord Forum

store or pass user from middleware

Answered
Glaucous-winged Gull posted this in #help-forum
Open in Discord
Glaucous-winged GullOP
Hello,

i want this middleware to protect my /protected route:
import { NextResponse, NextRequest } from "next/server";

export default async function middleware(request: NextRequest) {
  // validate jwt and fetch user from db else redirect

  const user = { name: "user1" };

  return NextResponse.next();
}

export const config = {
  matcher: '/protected',
}


here i verify jwt and fetch the user from db, whats the best way now to access/pass the user in a server component /protected/page.tsx or a route handler /protected/route.ts?
Answered by European sprat
Set headers or cookies with whatever details you want to check
View full answer

3 Replies

European sprat
Set headers or cookies with whatever details you want to check
Answer
Glaucous-winged GullOP
@European sprat thanks for the answer much appreciate!
Northeast Congo Lion
When I set a header to pass information from middleware to my route handler, the response from my route handler echoes that header. I cannot figure out how to delete the header from the response. the best I can do is set it to an empty string but I'd rather the end user not know what header names I'm using.