Next RSC: cookies().set() in validateRequest #1540
-
Hi there! I have followed the Next App Router tutorial and for the
However, Next's documentation says that a query from a server component should not have side-effects vercel/next.js#49843 (comment) Is this still open for discussion or a solved topic? Thanks :) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
The |
Beta Was this translation helpful? Give feedback.
-
Something I did to alleviate this issue (while also causing a new one, just slightly less brittle) was to use a route handler to set the cookie, but also be given a redirect url as a query parameter, similarly to this suggestion. Next.js hates granting server components the ability to set cookies because of how it designs streaming responses, yet route handlers give you full control of the request / response lifecycle, and therefore setting cookies is good-to-go. Now, the issue is actually redirecting. For instance, I'll take the code from the docs and adjust it slightly: import { lucia } from "@/utils/auth";
import { cookies, headers } from "next/headers";
const getUser = cache(async () => {
const sessionId = cookies().get(lucia.sessionCookieName)?.value ?? null;
if (!sessionId) return null;
const { user, session } = await lucia.validateSession(sessionId);
if ((session && session.fresh) || !session) {
const headersList = headers();
const referer = headersList.get('referer');
await fetch('/api/auth?redirectTo=' + referer);
}
return user;
}); Where |
Beta Was this translation helpful? Give feedback.
The
cookies().set()
throws an error when rendering the server component, which is patched by adding a try/catch