I’m working on a project using Next.js 14 and TypeScript where I have two roles: Buyers and Sellers. During the sign-up process, users need to select their role, and based on this selection, they should be redirected to the appropriate dashboard (either Buyer’s or Seller’s). However, I’m facing trouble implementing the sign-up API that handles this role-based logic.
Here’s an overview of the setup:
-
Sign-Up Flow:
User fills in the sign-up form with email, full name, and password.
After the form is submitted, the user selects whether they are a Buyer or a Seller.
Depending on the role, the user is redirected to the respective dashboard (/dashboard/buyer or /dashboard/seller).
-
Issues Encountered:
The API doesn’t properly handle the role-based redirection after the user submits the form.
Sometimes the user’s role isn’t saved correctly, or the redirection doesn’t happen as expected.
I’m using server actions for form submission and authentication in Next.js, avoiding API routes.
Here’s a simplified version of the code I’m using:
async function handleSignUp(data: FormData) {
"use server";
const role = data.get('role'); // buyer or seller
const email = data.get('email');
const password = data.get('password');
try {
// sign-up logic here
if (role === 'buyer') {
return { redirect: '/dashboard/buyer' };
} else if (role === 'seller') {
return { redirect: '/dashboard/seller' };
}
} catch (error) {
console.error('Sign-up error:', error);
}
}
What I’ve Tried:
-
Debugging the form data to ensure the role is passed correctly.
-
Checking the redirection logic after form submission.
-
Using server actions as a replacement for API routes.
Questions:
-
How can I properly implement the sign-up API to handle role-based redirection in Next.js 13?
-
Are there any best practices for managing role-based authentication and redirection in Next.js with server actions?
Any advice or examples would be greatly appreciated!
Assuming that you are saving user details (including role) in a table while user sign up, and you are using next-auth
for authentication, you can trigger next-auth
sign in function immediately after signup is success . following is a sample with CredentialsProvider
.
Provided middleware example will also handle the authorization logic. Customize it as per your requirement
It is always better to handle role based authentications from server side or middleware.
//next-auth route.ts file CredentialsProvider
CredentialsProvider({
//@ts-expect-error
async authorize(credentials, _req) {
//@ts-expect-error
const user: User = await getUser(credentials.email) // write your function to get user details including password, role from db;
// do user not exist check and other checks here
// validate password
const isValid = await verifyPassword(
//@ts-expect-error
credentials.password,
user.password
);
if (!isValid) {
throw Error("Wrong Password");
}
//here instead of image, I am returning user role
return {
image: user.role,
email: user.email,
name: user.name,
};
},
}),
// middleware.tsx (create this file on project root directory)
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import { withAuth } from "next-auth/middleware";
export default async function middleware(
req: NextRequest,
event: NextFetchEvent
) {
const PUBLIC_FILE = /.(.*)$/;
const pathname = req.nextUrl.pathname;
const token = await getToken({ req });
const isAuthenticated = !!token;
// token will have 3 keys: name, picture ("image" which we set on CredentialsProvider),email
if(isAuthenticated && pathname=="/dashboard"){
if(token.picture=="buyer"){
return NextResponse.redirect(new URL("/dashboard/buyer", req.url));
}else if(token.picture=="seller"){
return NextResponse.redirect(new URL("/dashboard/seller", req.url));
}
}
// Allow users to access URLs on following conditions, edit as per the requirement
if (
pathname.startsWith("/_next") ||
pathname. Includes("/api") ||
pathname. Includes("/signup")
PUBLIC_FILE.test(pathname) ||
isAuthenticated
) {
return NextResponse.next();
}
// apart from above conditions if user is not authenticated, it will redirect to /login route
const authMiddleware = withAuth({
pages: {
signIn: "/login",
},
});
// @ts-expect-error
return authMiddleware(req, event);
}
//sign in function
import { signIn } from "next-auth/react";
//after successful signup
const result = await signIn("credentials", {
redirect: false,
email: "email",
password:"password",
});
setLoading(false);
if (result && !result. Error) {
//success scenario, this is just a dummy route, middleware will redirect this as per the role
router.replace("/dashboard");
} else if (result?.error) {
//failed scenario
}