Back to Blog
Frontend engineeringRecent5 min

Next Auth

Next Auth

Authentication is a critical feature for modern web applications, and NextAuth.js v5 makes it easier than ever to implement secure, extensible authentication in your Next.js projects. The latest version brings exciting features, improved performance, and enhanced developer experience.

In this blog, we’ll dive into what’s new in NextAuth.js v5 and provide a step-by-step guide to integrating it into your Next.js application.

1. What’s New in NextAuth.js v5?

NextAuth.js v5 introduces several enhancements, including:

  • Improved Adapter API: A more consistent and flexible way to work with databases.
  • Enhanced TypeScript Support: Improved type safety for a better developer experience.
  • Customizable JWT Behavior: Greater control over JSON Web Tokens (JWT).
  • Improved Performance: Optimized server-side performance for large-scale applications.

2. Installing NextAuth.js v5

To get started, install the required dependencies:

npm install next-auth

Or with Yarn:

yarn add next-auth

3) Create the API Route

In the App Router, API routes are defined in the app/api directory. Create the following file:
/app/api/auth/[...nextauth]/route.js

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  secret: process.env.NEXTAUTH_SECRET,
  callbacks: {
    async session({ session, token }) {
      session.user.id = token.sub;
      return session;
    },
  },
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };


Here’s what’s happening:

  • Providers: Use Google as the OAuth provider. Add others as needed.
  • Secret: Ensure a secure secret is set in your .env file.
  • Callbacks: Customize the session or JWT logic as required.

4. Add Environment Variables

Update your .env.local file with provider credentials and other secrets:

GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
NEXTAUTH_SECRET=your-random-secret
NEXTAUTH_URL=http://localhost:3000


5. Using the useSession Hook in App Router

Create a Protected Page

To access authentication state, use the useSession hook from NextAuth.js:
/app/protected/page.jsx

"use client";

import { useSession, signIn, signOut } from "next-auth/react";

export default function ProtectedPage() {
  const { data: session } = useSession();

  if (!session) {
    return (
      <div className="p-6">
        <h1 className="text-2xl font-bold">You are not signed in</h1>
        <button
          onClick={() => signIn()}
          className="mt-4 rounded bg-blue-500 px-4 py-2 text-white"
        >
          Sign In
        </button>
      </div>
    );
  }

  return (
    <div className="p-6">
      <h1 className="text-2xl font-bold">Welcome, {session.user.name}!</h1>
      <p>Email: {session.user.email}</p>
      <button
        onClick={() => signOut()}
        className="mt-4 rounded bg-red-500 px-4 py-2 text-white"
      >
        Sign Out
      </button>
    </div>
  );
}

6. Customizing Authentication Behavior

Custom Login Page

Override default NextAuth.js pages by specifying custom routes in the authOptions:

export const authOptions = {
  pages: {
    signIn: "/auth/signin",
    error: "/auth/error",
  },
};

Create a Custom Sign-In Page

/app/auth/signin/page.jsx

"use client";

import { signIn } from "next-auth/react";

export default function SignIn() {
  return (
    <div className="p-6">
      <h1 className="text-2xl font-bold">Sign In</h1>
      <button
        onClick={() => signIn("google")}
        className="mt-4 rounded bg-blue-500 px-4 py-2 text-white"
      >
        Sign In with Google
      </button>
    </div>
  );
}

7. Securing API Routes and Pages

To protect server-side routes or fetch session data, use the getServerSession method.

Example: Server-Side API Protection

/app/api/protected/route.js

import { getServerSession } from "next-auth";
import { authOptions } from "../auth/[...nextauth]/route";

export async function GET(req) {
  const session = await getServerSession(authOptions);

  if (!session) {
    return new Response("Unauthorized", { status: 401 });
  }

  return new Response(JSON.stringify({ message: "Welcome!" }));
}

Conclusion

With Next.js 15 App Router and NextAuth.js v5, authentication is both straightforward and flexible. Whether you need simple OAuth integration or custom authentication flows, this setup can scale with your project.

Try it out, and let us know how it fits your workflow! 🚀

Let me know if you'd like further assistance or enhancements for specific use cases!