I am experiencing a problem with authentication in my Next.js application using NextAuth.js. The issue specifically pertains to the redirection after successful login. Here is an overview of my setup:
NextAuth.js Configuration (app/api/auth/[...nextauth.js]
):
import NextAuth from "next-auth/next";
import CredentialsProvider from "next-auth/providers/credentials";
const authOptions = {
providers: [
CredentialsProvider({
id: 'credentials',
name: "credentials",
credentials: {},
async authorize(credentials, req) {
const { email, password } = credentials;
if (email !== "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e030b2e0940dl@coo.com">c@o@%m</a>" || password !== "123") {
throw new Error("invalid credentials");
}
return {
id: "2453",
name: "J Smith",
//obfuscated email here
role: "admin",
};
},
}),
],
session: {
strategy: "jwt",
},
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: "/login", //correct signin page specified
},
callbacks: {
jwt(params) {
if (params.user?.role) {
params.token.role = params.user.role;
}
return params.token;
},
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
This section outlines the configuration for NextAuth.js where I set up authentication providers and callbacks.
Next.js Sign-In Page (app/auth/login/page.jsx
):
"use client";
import Image from "next/image";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { signIn } from "next-auth/react";
//code continuation ...
This page is where users input their login details and submit the form.
Middleware (middleware.js
):
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server"
// middleware code continued ...
The middleware secures specific routes ensuring only authenticated users with designated roles can access them.
Issue Description:
Despite providing correct credentials, instead of redirecting straight to the /dashboard
page, upon submitting the login form, the application redirects to an unexpected URL:
http://localhost:3000/login?callbackUrl=http%3A%2F%2Flocalhost%3A3000%2Fdashboard
The anticipated behavior is direct redirection to /dashboard
. Though the authentication succeeds, the redirection is inaccurate.
Steps Taken:
Ensured the
signIn
function was imported fromnext-auth/react
on the sign-in page.Updated the
jwt
callback within NextAuth.js to incorporate the user's role into the token.
pages
settings in NextAuth.js correctly point to the signIn
page as /login
.- Confirmed the middleware accurately safeguards the
/dashboard
route for 'admin' role users.
Your insights or suggestions regarding this redirection challenge would be highly appreciated. Thank you for your support!