Trouble Implementing Sign-Up API with Role-Based Logic (Buyers and Sellers) in Next.js

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:

  1. 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).

  2. 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:

  1. How can I properly implement the sign-up API to handle role-based redirection in Next.js 13?

  2. 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
    }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật