Next.js Discord

Discord Forum

can we access cookies in any component setting it in middleware

Answered
Red-tailed wasp posted this in #help-forum
Open in Discord
Avatar
Red-tailed waspOP
In middleware I have saved variable in cookies

const res = NextResponse.next()
res.cookies.set('next', 'fast')

Can I access this cookie in any component

**using pages router
Answered by Marchy
You could just do this, I'm not sure what you mean by returning both a response and a redirection.
export function middleware(request) {
  // Create a response object for redirection
  const response = NextResponse.redirect(new URL("/login", request.nextUrl));

  // Store the data in a cookie
  response.cookies.set('payload', JSON.stringify({ key: 'value' }));

  // Return the response
  return response;
}
View full answer

6 Replies

Avatar
The short answer is yes, but the longer answer is maybe? I guess it depends on what you're trying to do
Avatar
Red-tailed waspOP
@Marchy how can we access can you share any reference how can I do that
Avatar
@Red-tailed wasp <@203709756689350656> how can we access can you share any reference how can I do that
Avatar
Depends. If they're not HTTP only
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

If they are, you'd have to check it in your getServerSideProps and/or pass it as a prop to the page
Avatar
Red-tailed waspOP
@Marchy

I need to send response and NextResponse both in return can you help me out how can i do that, in below case it is redirecting to the url, but cookies is not setting up. and if i only send response in return then cookie setting.
But i need to add both response and redirection.

export function middleware(request) {

const response = NextResponse.next();
response.cookies.set('next', 'fast')

return response && NextResponse.redirect(
new URL("/login", request.nextUrl)
);
}
Avatar
@Red-tailed wasp <@203709756689350656> I need to send response and NextResponse both in return can you help me out how can i do that, in below case it is redirecting to the url, but cookies is not setting up. and if i only send response in return then cookie setting. But i need to add both response and redirection. export function middleware(request) { const response = NextResponse.next(); response.cookies.set('next', 'fast') return response && NextResponse.redirect( new URL("/login", request.nextUrl) ); }
Avatar
You could just do this, I'm not sure what you mean by returning both a response and a redirection.
export function middleware(request) {
  // Create a response object for redirection
  const response = NextResponse.redirect(new URL("/login", request.nextUrl));

  // Store the data in a cookie
  response.cookies.set('payload', JSON.stringify({ key: 'value' }));

  // Return the response
  return response;
}
Answer
Avatar
Red-tailed waspOP
Thanks brother that worked, there is a case in my office project in that i need to do this.