I am using NextJS I have been struggled with this problem for quite some time. Essentially, I want to sepearte logic and UI in my project. I want to only paste in the necessary parameters (e.g. methods, URL, and body) in the component and the service folder is where it actually makes the fetch call and handles the logic.
I want my service folder to retrieves the cookies from when user login, and pastes that along with the fetch call, and the components don’t have to worry about cookie and such. NextJS does provide two ways to access the cookie: through NextRequest object and the cookie function directly from next/headers. However, the cookie function doesn’t run inside a client component, and most of my components have “use client”. For the NextRequest object, I managed to get the cookie from the route handler, but the api is public and it can be vulnerable to CSRF or XSS attack (I am not an expert on this). What I am afraid is that someone can fake a link that make a get request to my public api in the route handler and trick my user to click it. That way, they can get the access token that I store in the cookie.
So, I want to know if anyone has an elegant way of solving this? Is my approach a sensible one (seperating logic and UI)? Am I just complicating things? Thank you you guys for reading this far.
Huy Nguyen Quang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.