DEV3 Technologies home

DEV3 Developer Forum

How do I get the logged-in user in a Server Component with Auth.js (NextAuth v5)?

Next.js helpSolved0 views
dev3 ·

I migrated from NextAuth v4 to Auth.js v5. getServerSession(authOptions) no longer exists. How do I read the session in server components, route handlers and middleware?

#nextjs#next-auth#authjs

0

1 reply

dev3 · Accepted answer

In Auth.js (NextAuth v5) you create one config file that exports auth, handlers, signIn and signOut.

// auth.ts
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Credentials({
      async authorize(credentials) {
        // verify password hash against your DB, return user or null
        return null;
      },
    }),
  ],
  session: { strategy: "jwt" },
  callbacks: {
    jwt({ token, user }) {
      if (user) token.id = user.id;
      return token;
    },
    session({ session, token }) {
      if (token.id) session.user.id = token.id as string;
      return session;
    },
  },
});
// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;

Reading the session

// server component
import { redirect } from "next/navigation";
import { auth } from "@/auth";
export default async function Page() {
  const session = await auth();
  if (!session?.user) redirect("/login");
  return <p>{session.user.email}</p>;
}
// route handler
export async function GET() {
  const session = await auth();
  if (!session) return new Response("Unauthorized", { status: 401 });
  return Response.json({ id: session.user.id });
}

Client components use useSession() inside <SessionProvider>, or just pass user data as props from the server.

Env names

v5 prefers AUTH_SECRET (and AUTH_URL behind proxies; AUTH_TRUST_HOST=true on non-Vercel hosts). NEXTAUTH_* still works in many cases.

Pitfall: if you run several apps on different localhost ports they share cookies and you get JWTSessionError or 431 errors. Set a distinct cookie name per app in the config (cookies.sessionToken.name).

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.