skip to Main Content

I am new to Next js and I am facing a problem whole day

This is my api for checking in mongoDB if user exists


import {connect} from '../../../../lib/mongodb';
import User from '../../../models/userModel';

export async function POST(req, res) {
    try {
        // Get email from request body
        const {email} = await req.json();

        // Connect to database
        await connect();

        // Find user by email
        const user = await User.findOne({email});

        // If user exists, return error
        if (user) {
            return res.status(400).json({message: "User already exists"});
        } else {
            // Return response
            return res.status(201).json({message: "Email is non registered."});
        }
    } catch (error) {
        console.error(error);
        return res.status(500).json({message: "Something went wrong while register"});
    }
}

TypeError: res.status is not a function

I tried to switch req with res, I tried to use NextResponse and NextRequest but I read that they are used only in middleware

2

Answers


  1. You can write this:

    const response = {
      success: 'Logged in successfully'
    };
    return new Response(JSON.stringify(response), {
      status: 200,
      headers: {
        "message": "Blurblur~"
      },
    });
    }
    
    else 
      
    return NextResponse.status(200).json({
      error: 'Authentication failed'
    });
    
    
    Login or Signup to reply.
  2. You should be using the Response object

    if (user) {
       return new Response.json({ message: "User already exists" },
           {
               status: 200,
               headers: {
                   "content-type": "application/json"
               }
           })
    }
    else {
       return new Response.json({ message: "Email is non registered" },
           {
               status: 404,
               headers: { "content-type": "application/json" }
           })
    }
    

    TypeScript Warning: Response.json() is only valid from TypeScript 5.2. If you use a lower TypeScript version, you can use NextResponse.json() for typed responses instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search