In practice, a SaaS application often includes protected routes, pages, or components that should only be accessible to authenticated users.
In order to implement such logic, we need a mechanism to verify whether a user is signed in. Auth.js provides a straightforward way to handle this, making it easier to secure your application.
Checking if the user is signed in
When the user signs in, a piece of information, referred to as session, will be created and saved inside the database. The session will persist until it expires or the user manually signs out. As long as the session exist, the user is seen as authenticated.
Auth.js comes with a method that allows you to easily retrieve the session. Go back to libs/auth.js
and notice that an auth()
method is exported from here.
libs/auth.js
1. . .
2
3export const { handlers, signIn, signOut, auth } = NextAuth({
4 adapter: PrismaAdapter(prisma),
5 providers: [. . .],
6 pages: {. . .},
7});
The method doesn't require any additional argument, just execute it inside server components, API routes, or server actions, and it will return the user session.
If the session exist, the user is authenticated, and if not, the user is not authenticated. You can then implement the logic accordingly.
1import { auth } from "@/libs/auth";
2
3const session = await auth();
4
5if (session) {
6 // User is signed in
7} else {
8 // User is NOT signed in
9}