Redirecting unauthenticated users in Nextjs 16 cache components #87123
Unanswered
pauksztello
asked this question in
Help
Replies: 1 comment 1 reply
-
|
Hey! I totally get the confusion here. Let me break it down simply. Think of it like a security guard at a building entrance:
With Protected Pageexport default async function ProtectedPage() {
// Guard at the door (runs every request)
const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect("/login");
// Rooms inside (can be cached)
return (
<Suspense fallback={<Loading />}>
<CachedContent />
</Suspense>
);
}
async function CachedContent() {
"use cache";
return <div>Your protected content</div>;
}Login Page (redirect if already logged in)Same logic - guard first, then content: export default async function LoginPage() {
const session = await auth.api.getSession({ headers: await headers() });
if (session) redirect("/dashboard");
return <LoginForm />;
}No extra wrapper components needed! Quick TipIf you call Docs: Next.js Auth Guide |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
We’re experimenting with Next.js 16 cacheComponents, and we’re struggling to figure out the right way to redirect users based on whether they’re authenticated.
Right now, we check for a user session in an RSC component on each page and redirect if the session is invalid:
We’re not sure what the proper way to do this with cache components.
I guess we should do the same, but only in nested components and in multiple places where data is used? We don’t like having to repeat that in multiple places.
It gets even weirder on the login page, where we don’t actually use any user data from the session. Do we create a separate component just for redirecting?
We are using a proxy (middleware), but we only check for the cookie for optimistic redirects.
Thanks!
Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions