Enable Dark Mode!
how-to-add-authentication-using-authjs-in-nextjs.jpg
By: Alan Joy

How to Add Authentication Using Auth.js in Next.js

Technical

Authentication is one of the most important features of any modern web application. Whether you're building a SaaS platform, admin dashboard, or social app, you need a secure way for users to sign in and access protected content. In this beginner-friendly guide, we’ll learn how to add authentication to a Next.js application using Auth.js. We’ll implement a simple login system and protect pages using sessions.

What is Auth.js?

Auth.js is a modern authentication library for JavaScript applications. It was previously known as NextAuth.js and is widely used for authentication in Next.js apps. Auth.js supports many authentication methods including:

  • Email & Password
  • OAuth providers (Google, GitHub, etc.)
  • Magic links
  • Custom providers
  • JWT and session-based authentication

Prerequisites

If you don’t have a project yet, create one with:

npx create-next-app@latest next-auth-example
cd next-auth-example

Step 1: Install Auth.js

npm install next-auth

Step 2: Create the Auth Route

Auth.js requires a special API route for handling authentication. Create the following file:

app/api/auth/[...nextauth]/route.ts

Add the following code:

import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
const handler = NextAuth({
  providers: [
    Credentials({
      name: "Credentials",
      credentials: {
        email: {},
        password: {}
      },
      async authorize(credentials) {
        const user = {
          id: "1",
          name: "John Doe",
          email: credentials?.email
        }
        if (credentials?.email === "admin@test.com" &&
            credentials?.password === "password") {
          return user
        }
        return null
      }
    })
  ],
  session: {
    strategy: "jwt"
  },
  pages: {
    signIn: "/login"
  }
})
export { handler as GET, handler as POST }

What this does

  • Adds a Credentials provider
  • Validates email and password
  • Returns a user object if authentication succeeds
  • Uses JWT session strategy

Step 3: Create a Login Page

Next, create a login page

app/login/page.tsx

Add the following code:

"use client"
import { signIn } from "next-auth/react"
import { useState } from "react"
export default function LoginPage() {
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    await signIn("credentials", {
      email,
      password,
      callbackUrl: "/dashboard"
    })
  }
  return (
    <div>
      <h2>Login</h2>
      <form onSubmit={handleSubmit}>
        <input
          type="email"
          placeholder="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <input
          type="password"
          placeholder="Password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <button type="submit">
          Login
        </button>
      </form>
    </div>
  )
}

How it works

  • Uses signIn() from Auth.js
  • Sends email and password to the credentials provider
  • Redirects to /dashboard after login

Try logging in with:

Email: admin@test.com
Password: password

Step 4: Add Session Provider

To use authentication in your React components, you must wrap your app with SessionProvider. Edit your root layout:

app/layout.tsx
"use client"
import { SessionProvider } from "next-auth/react"
export default function RootLayout({
  children
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <body>
        <SessionProvider>
          {children}
        </SessionProvider>
      </body>
    </html>
  )
}

Step 5: Access the User Session

Now we can access the logged-in user.

Example dashboard page:

app/dashboard/page.tsx
"use client"
import { useSession, signOut } from "next-auth/react"
export default function Dashboard() {
  const { data: session } = useSession()
  if (!session) {
    return <p>Not authenticated</p>
  }
  return (
    <div>
      <h1>Dashboard</h1>
      <p>
        Welcome {session.user?.email}
      </p>
      <button onClick={() => signOut()}>
        Logout
      </button>
    </div>
  )
}

What this does

  • useSession() retrieves the user session
  • Displays user information
  • Adds a logout button

Authentication is a critical feature for any modern web application. Thankfully, Auth.js makes it simple to add secure authentication to your Next.js project. Auth.js supports many advanced features such as OAuth providers, database adapters, and email authentication, making it a powerful solution for production applications. If you're building SaaS platforms, dashboards, or collaborative tools, adding a reliable authentication system like Auth.js is essential.

Start experimenting with additional providers and database integrations to build a fully secure authentication system for your Next.js apps.

To read more about How to Use the proxy.ts File in Next.js 16, refer to our blog How to Use the proxy.ts File in Next.js 16.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, KINFRA Techno Park
Kakkanchery, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message