I don't understand how to get cookies into request to middleware
Unanswered
Palomino posted this in #help-forum
PalominoOP
I have auth tokens in localstorage that i want in the request to middleware:
but the cookie headers are always null. How can i add those localstorage values to the request, so the middleware can receive identity tokens as the user switches routes?
export async function middleware(request: NextRequest) {
const cookieHeader = request.headers.get('cookie');
}but the cookie headers are always null. How can i add those localstorage values to the request, so the middleware can receive identity tokens as the user switches routes?
4 Replies
Transvaal lion
localstorage is browser spesfic. So middleware that only run in the edge environment don't have access to browser apis.
I would move the token to a http only cookie. Then you will be able to read it from the middleware request header https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies
I would move the token to a http only cookie. Then you will be able to read it from the middleware request header https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies
@Transvaal lion localstorage is browser spesfic. So middleware that only run in the edge environment don't have access to browser apis.
I would move the token to a http only cookie. Then you will be able to read it from the middleware request header https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies
PalominoOP
Maybe i'm dumb but everything i find online is for how to put the cookie into a singular request. But middleware is called every time a user switches pages. So how do you globally set this cookie?
Transvaal lion
Cookies is sent on each page request, so every middleware or page or layout component that is render on the server will have access to the cookies from the HTTP request.
So i depends where you get your auth data from that you want to set in a cookie so it can be read in a middleware or in other page, layout, api routes and actions.
Dont have much context so not sure what your trying to achieve except that you wanted to read from localstorage. That can only be done in a client component that runs in your browser 🙂
So i depends where you get your auth data from that you want to set in a cookie so it can be read in a middleware or in other page, layout, api routes and actions.
Dont have much context so not sure what your trying to achieve except that you wanted to read from localstorage. That can only be done in a client component that runs in your browser 🙂