Intro
I'm new to development and it's more of a hobby for me. As part of my personal project, I faced a simple task: client-server interaction between a NestJS server and Next.js client. Following the latest requirements, I implemented authorization through a pair of tokens with different lifetime and storing them in the client's browser cookie. And this is where the adventure began.
Problem
Next.js imposes very strict restrictions on working with cookies, so you can't just write new tokens received. This must happen in Server Actions or Route Handlers. You can also do it in middleware. The Internet is full of instructions on how to bypass these restrictions using Axios, third-party libraries for working with cookies, wrapping requests to an external server in Route Handlers, etc.
I tried them all, and none of them worked well.
In addition, I strongly dislike the idea of putting something in the system to replace existing tools because I couldn't figure them out. The Next.js developers designed it with fetch() in mind as a tool for executing queries, deliberately put restrictions on working with cookies, created Server Actions and Route Handlers for purposes unrelated to third-party APIs.
Thus, the question arises: how to implement the process of updating tokens with storage in browser cookies using built-in Next.js tools?
Continue in the first comment -->