Leveraging Next.js to efficiently handle multiple asynchronous requests with NextResponse

I have developed a login/signup application using NextJS. When attempting to log in, the logic in my route.ts file sends requests to a MongoDB database to check if the user exists and if the password is correct. However, instead of receiving the expected 400 error response when entering wrong credentials, I am consistently getting a 500 Internal Server Error. What could be causing this issue with my current logic?

Here is the code snippet:

import { connect } from "@/dbConfig/dbConfig";
import User from "@/models/userModel";
import { NextRequest, NextResponse } from "next/server";
import bcryptjs from "bcryptjs";
import jwt from "jsonwebtoken";

connect();

export async function POST(request: NextRequest) {
  try {
    const reqBody = await request.json();
    const { password, email } = reqBody;

    console.log(reqBody);

    // Check if user exists
    const user = await User.findOne({ email });
    console.log(user.password);
    if (!user) {
      NextResponse.json(
        { message: "User does not exist" },
        { status: 400, statusText: "User does not exist" }
      );
    }

    // Check if password is correct
    const validPassword = await bcryptjs.compare(password, user.password);
    if (!validPassword) {
      return NextResponse.json(
        {},
        { status: 400, statusText: "Invalid Password" }
      );
    }

    // Create token data
    const tokenData = {
      id: user._id,
      username: user.username,
      email: user.email,
    };
    // Create token

    const token = await jwt.sign(tokenData, process.env.TOKEN_SECRET!, {
      expiresIn: "1d",
    });

    const response = NextResponse.json({
      message: "Login successful",
      success: true,
    });

    response.cookies.set("token", token, { httpOnly: true });

    return response;
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

Answer №1

 if (!user) {
      NextResponse.json( // don't forget to include the return keyword
        { message: "User not found" },
        { status: 400, statusText: "User not found" }
      );
    }

I mistakenly omitted the return statement. It should read as return NextResponse.json(...)

:D

Answer №2

It appears that the issue lies within

console.log(user.password)

As you are logging the user's password without first verifying if the user object is null. This can result in an error being thrown when trying to access the password property of a null user, leading to your catch block being triggered.

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

Issue with Google Tag Manager click event not propagating to parent element

I am currently configuring Google Tag Manager for a client's website and encountering difficulties in getting click event tags to activate. Although I have set the trigger to activate based on the button's CSS selector, the actual button contain ...

Creating a Login Form with Node.js and MongoDB

Currently, I am working on a node.js application that is connected to a remote mongoDB server. Inside the database are specific custom codes that have been created and shared with selected users. The main objective is to restrict access to the rest of the ...

Leverage the power of the modal component in your ReactJS

I'm facing an issue with the antd library. Even after installing it from the official site and importing the modal component, it's not functioning properly for me. I've carefully checked everything in my code and everything seems to be fine. ...

Tips for iterating through an array of images and displaying them in a React component

I am working on a project in my react app where I have 5 images that I want to cycle through indefinitely. The goal is to create an animation where a light bar appears to be constantly moving. https://i.sstatic.net/8tdfV.png The shifting dot in each imag ...

Guide on implementing twitch-passport for authentication in Node.js using Express and Passport Next

Currently, I am in the process of implementing authentication for my website. While I have plans to incorporate additional signup/connect account options in the future, at present, my primary focus is on integrating Twitch authentication. For server-side r ...

I would love to hear your suggestions for a custom select element plugin in jQuery

After browsing multiple options online, I decided to turn to the expertise of the Stack Overflow community to ask for recommendations based on personal experience. I am specifically in search of a plugin that can substitute a select element with a custo ...

Display logo when website has been scrolled

On my website, I want to display a logo in the header only when the site has been scrolled. I attempted to accomplish this with JavaScript: if(document.getElementById("div").scrollTop != 0){ document.write("<img src='logo.jpg'>"); } How ...

Why is my NextJs app loading slowly on Safari but quickly on Chrome?

Currently, I am in the process of developing a web app using nextjs. I have encountered some issues with linking to pages, particularly the home page which contains multiple svgs and images. The performance lags when using Safari, as it does not show a loa ...

Issue with React app: IconMenu does not expand when clicked

Seeking assistance with a react app and IconMenu from material-ui. I've been researching similar issues extensively but haven't found a solution yet :( In the code below, I am looking to manually trigger the expansion of a menu - this is essenti ...

What is the process for integrating the Bootstrap JS library into a Next.js project?

My upcoming project involves server-side rendering with Next.js, and I plan to incorporate Bootstrap into it. After some research, I decided to import Bootstrap into my root layout like this: import { Inter } from "next/font/google"; import " ...

Guide on using JavaScript to implement the universal CSS selector

One technique I frequently employ is using the CSS universal selector to reset the dimensions in my HTML document: * { border: 0; margin: 0; padding: 0; } I wonder if a similar approach can be achieved with JavaScript as well? When it come ...

Looping through multi-dimensional JSON objects with jQuery

Hello there, I'm currently facing some challenges in getting the screen below to work properly: Project progress screen I have generated the following JSON data from PHP and MYSQL. My goal is to display the project alongside user images and names whe ...

Dealing with Cross-Origin Resource Sharing (CORS) problem when using Google Cloud Storage Signed

I'm looking to empower artist clients to easily upload images to Cloud Storage by utilizing Signed URLs. Here's the backend script used to fetch the signed URL, which resides behind a Google Cloud load balancer: (Does the presence of a load bal ...

PHP - Retrieve fully rendered HTML content from an external page

I am a beginner when it comes to AJAX and PHP, and I have been experimenting with using a PHP HTML DOM Parser to retrieve the HTML from an external website. However, I have encountered an issue where the fetched HTML is only the content that was initially ...

Adding additional functionalities to ng-blur within the controller: A step-by-step guide

I am seeking to enhance the functionality of ng-blur for all input and textarea fields by adding a new function. These elements already have an existing ng-blur defined in the HTML, and my goal is to incorporate a new function into this existing setup from ...

What are the steps to modify the camera type in Three.js?

I have added a dropdown list on the page for selecting between two cameras - Perspective and Orthographic. Currently, my Three Scene is using a perspective Camera. I would like to dynamically change the camera to "Orthographic" when selected in the dropdow ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...

Issue arose when attempting to utilize the API key as an environmental variable within the Butter CMS library while working within the async

After migrating my website from Drupal to Vue, I decided to enhance the SEO performance by transitioning it to Nuxt. However, I am encountering difficulties in setting and utilizing a private API key as an environment variable in a component with the Butte ...

The ExtJS Grid Filter is being triggered excessively

I am working on an ExtJS 6.2 grid that uses the 'classic' API. Although I am not very experienced with Ext, we have a grid component that we reuse with small modifications in different applications. In one of our apps, we have a text field for fi ...

Using jquery to toggle active nav links in Bootstrap

I'm currently working on integrating a jQuery function to automatically update the active status of the navigation links in my Bootstrap Navbar. The structure involves a base HTML file that extends into an app-specific base file, which is further exte ...