Next js Authentication by credentials using APP ROUTER Method

Create .env file with the following domain URL

like

NEXTAUTH_URL=http://localhost:3000/

Create the route.js file

app/api/auth/[…nextauth] in the following path

import NextAuth from "next-auth/next";

import CredentialsProvider from "next-auth/providers/credentials";

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

export const authOptions = {

providers: [

  CredentialsProvider({

    name: "Credentials",

    credentials: {

      username: { label: "Username", type: "text", placeholder: "User Name" },

      password: { label: "Password", type: "password" , placeholder: "Password" },

      rememberMe: {  // New field for Remember Me

        label: "Remember Me",

        type: "checkbox",

      },

    },

    authorize: async function(credentials, req) {

       const user = { id: "1", name: "Test User", email: "test@test.com" , password: "password" };

       const { username, password, rememberMe } = credentials;

      if (user && user.password === password) {

        return user;

      } else {

        return null;

      }

    }

  })

],

session: {

  jwt: true,

  maxAge: 30 * 60, 

  updateAge: 24 * 60,

},

};

export const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

Middleware.js file in the following path

src/middleware.js

import { getSession } from "next-auth/react";
import { NextResponse } from "next/server";




export async function middleware(req, ev) {


  const NEXTAUTH_ENABLE = process.env.NEXTAUTH_ENABLE;
  
  console.log(NEXTAUTH_ENABLE);


  if (NEXTAUTH_ENABLE === 'true') {
  const requestForNextAuth = {
    headers: {
      cookie: req.headers.get("cookie")
    }
  }
  const session = await getSession({ req: requestForNextAuth })
  if (session) {
    console.log(session.user.name)
     return NextResponse.next()
  } else {
    return NextResponse.redirect(new URL('/api/auth/signin', req.url))
  }
} else {
  // NEXTAUTH_ENABLE is false, disable authentication
  return NextResponse.next();
}
}
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|.*.png$).*)'],
}


Leave a comment

Your email address will not be published. Required fields are marked *