Struggling with integrating sign-up API that includes role-based logic for buyers and sellers in Next.js

I am currently developing a project with Next.js 14 and TypeScript that involves managing two distinct roles: Buyers and Sellers. As users sign up, they are required to select their role, which then determines the dashboard they should be redirected to (either Buyer's or Seller's). However, I am encountering challenges when it comes to implementing the sign-up API responsible for handling this role-based logic.

Let me provide you with an outline of the current setup:

  1. The Sign-Up Process:

    Users complete a sign-up form with their email, full name, and password details.

    After submitting the form, users must indicate whether they are a Buyer or a Seller.

    Based on their role selection, users should be directed to the appropriate dashboard (/dashboard/buyer or /dashboard/seller).

  2. Issues Faced:

    The API is struggling to properly manage the role-based redirection post-form submission.

    At times, the user's role is not saved correctly, leading to unexpected issues with redirection.

In my implementation, I am utilizing server actions for form submission and authentication within Next.js instead of conventional API routes.

Below is a simplified snippet showcasing the code I am working with:

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);
  }
}

Actions Taken So Far:

  • Thoroughly debugging the form data to ensure accurate passage of the role value.

  • Reviewing the redirection flow following form submission.

  • Utilizing server actions as a substitute for traditional API routes.

Queries:

  1. What steps can I take to effectively implement the sign-up API for managing role-based redirection in Next.js 13?

  2. Do you have any recommended strategies for handling role-based authentication and redirection using server actions in Next.js?

Your guidance and examples would be highly valuable!

Answer №1

When storing user details, including their role, in a table during sign-up and utilizing next-auth for authentication, you can automatically trigger the sign-in function of next-auth right after successful sign-up. Below is an example implementation using CredentialsProvider.

The middleware example provided also manages the authorization logic, which can be customized based on specific requirements.

It is recommended to handle role-based authentications from the server-side or middleware for better security.

//Code snippet from next-auth route.ts file with CredentialsProvider

CredentialsProvider({
      //@ts-expect-error
      async authorize(credentials, _req) {
         //@ts-expect-error
        const user: User = await getUser(credentials.email); // implement function to retrieve user details including password and role from database
        // perform checks such as user existence and validation
        // validate user password
        const isValid = await verifyPassword(
          //@ts-expect-error
          credentials.password,
          user.password
        );
        if (!isValid) {
          throw Error("Incorrect Password");
        }
        //instead of image, returning user role here
        return {
          image: user.role,
          email: user.email,
          name: user.name,
        };
      },
    }),

//Middleware example in middleware.tsx (create this file in 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;
  
  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));
      }
  }

  if (
    pathname.startsWith("/_next") ||
    pathname.includes("/api") ||
    pathname.includes("/signup") || 
    PUBLIC_FILE.test(pathname) ||
    isAuthenticated
  ) {
    return NextResponse.next();
  }

  const authMiddleware = withAuth({
    pages: {
      signIn: "/login",
    },
  });
  
  return authMiddleware(req, event);
}

//Function for signing in

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 - dummy route; middleware will handle redirection based on role
      router.replace("/dashboard");
    } else if (result?.error) {
      //failed scenario
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Emphasize the Jqgrid row when clicked on, but do not check the multiselect checkbox

Is there a method in jQgrid to highlight a row when clicked without selecting the multiselect checkbox? I attempted using Multiboxonly = true as suggested by Oleg on Your assistance would be greatly appreciated, as this issue is currently hindering progr ...

Utilize a single submit button to navigate through multiple pages dynamically using JavaScript

I would like to navigate to different rooms with just one button using JavaScript. For instance, there are three rooms: "Kitchen, Toilet, and Bedroom". How can I utilize JS to enter any of these rooms based on my selection? If I input "kitchen" in the text ...

The fetch API is being restricted, however, AJAX and XHR are still operational

I made an API call to a URL shortener and encountered different responses using Fetch, JQuery, and XHR. Why is Fetch returning a 400 error while the other methods work smoothly? Even after trying mode: 'no-cors' and "crossDomain": true in the re ...

How to include THREE.js in a Node module along with custom variables and functions

I have been working on adapting a THREE.js project that originally included JavaScript files directly in HTML into a node module-based setup. My goal is to utilize webpack to bundle the project into a single file (bundle.js) so that the HTML only needs to ...

"Utilize browser detection to direct users to appropriate pages - whether by using htaccess or another method

I'm in the process of creating a website and I've noticed that it looks quite bad on Firefox and IE. I was wondering if you could help me figure out how to redirect users to different pages based on the browser they are using. Since I am not an ...

What are the best practices for implementing serialization in NestJS?

Recently, I delved into a fresh NestJs project and encountered a hurdle while trying to integrate serialization. The goal was to transform objects before sending them in a network response. Initially, everything seemed to be working smoothly until I attemp ...

Ways to ensure the height of an element is consistent across various device modes

Testing out the angular-youtube-embed plugin with Chrome Dev tools' device mode, I wanted to see how the YouTube element would appear. Here's my code: <div class="fixed-header my-video"> <div style="padding:0px;"> <yo ...

send the value of a variable from a child component to its parent

I have created a typeahead component within a form component and I am trying to pass the value of the v-model from the child component to its parent. Specifically, I want to take the query model from the typeahead component and place it in the company mode ...

Using the md: hidden feature in Nextjs + tailwindcss + NextUI for mobile end adaptation does not function as intended

For my website , I used nextjs14+typescript+tailwindcss. Initially, I focused on the web version but later decided to optimize it for mobile devices. During the mobile adaptation process, I wanted to implement the "block md:hidden" functionality. This woul ...

What is the best way to extract individual objects from several arrays and consolidate them into a single array?

Currently, I have a collection of objects stored in a variable called listOfObjects. They are not separated by commas because I utilized the Object.entries method to extract these values from another array. console.log(listOfObjects) outputs { q: 'L ...

Retrieving the value of a duplicated button in AngularJS

I have implemented a basic HTML table using AngularJS to display data for each item in my "names" array. Each item represents an object with various attributes such as Name, id, etc. Along with each row in the table, I have included a button. However, I am ...

Is the jQuery ajax .done() function being triggered prematurely?

Struggling with a problem here. I'm dealing with this code (simplified): var initializeZasilkovna = function () { // Initialize object window.packetery.initialize(); }; // Check if the object doesn't exist if (!window.packetery) { // It ...

Retrieving object key value from an array using Underscore.js

Hey there, I'm facing a challenge where I need to extract the values of wave1 and wave2 from an array using underscore.js. array = [{"id":1,"name":"Monoprix", "pdv":16,"graph":[{"wave1":22,"wave2":11}]} ; I attempted the following: $scope.wave1 = a ...

Experiencing SyntaxError when utilizing rewire and mocha for Node.js testing. Unexpected token encountered

Trying to test a function exported from a nodejs file, I am utilizing q to manage promises. The function returns a promise that is either resolved or rejected internally through a callback. Within this callback, another function from a different location i ...

A different method for duplicating a photo and viewing it in a larger size

I am new to coding and currently working with Reactjs. For my latest project, I am creating a gallery of photos sourced from a flickr api service. Each image in the gallery will come with two buttons: 1. Duplicate: This button should duplicate the image ...

What is the proper way to provide parameters for express.use to avoid encountering a type error?

When attempting to use the path string in this code snippet within the function, an error is thrown. The argument type string cannot be assigned to the parameter type RequestHandler<RouteParameters>    The assigned type does not contain call si ...

`sendNodejs header not being transmitted during connection``

My nodejs application utilizes stomp to connect to a server using websockets. However, I am encountering an issue where the application is failing to send the headers that I have specified. Despite referring to clear documentation and examples on how to in ...

Retrieve an item from an array by utilizing the `array.some()` method instead of just getting

I am currently attempting to utilize the array.some function to traverse through a dataset and retrieve my field when the specified condition is met. However, what I'm experiencing is that instead of obtaining the variable (which holds details to an ...

What are some techniques for maintaining a nodejs chat application widget across page refreshes?

Currently, I am developing a chat application that includes chat widgets for site visitors using nodeJS. One issue I am facing is how to maintain visitor details across page loads. It is important to me that once a visitor initiates a chat, they do not hav ...

The problem with JQuery ajax arises when attempting to send a file input value

I am facing an issue when trying to send a file value to PHP using the ajax code below. The file gets uploaded successfully and stored in the database, but the problem arises when I get redirected. // form data submission $('#myForm').submit(fun ...