Access cookies in middleware?
I found two patterns to access cookies in middleware, are they equally good?
1. From https://nextjs.org/docs/app/building-your-application/authentication#optimistic-checks-with-middleware-optional
2. From https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies
Routing: Middleware | Next.js
Learn how to use Middleware to run code before a request is completed.
Building Your Application: Authentication | Next.js
Learn how to implement authentication in your Next.js application.
Solution:Jump to solution
It seems that the first option is better for long term maintenance: https://nextjs.org/docs/app/api-reference/functions/cookies#good-to-know
Functions: cookies | Next.js
API Reference for the cookies function.
2 Replies
Solution
It seems that the first option is better for long term maintenance: https://nextjs.org/docs/app/api-reference/functions/cookies#good-to-know
Functions: cookies | Next.js
API Reference for the cookies function.
You're right, thanks!
cookies is an asynchronous function that returns a promise. You must use async/await or React's use function to access cookies. In version 14 and earlier, cookies was a synchronous function. To help with backwards compatibility, you can still access it synchronously in Next.js 15, but this behavior will be deprecated in the future.