Next.js Discord

Discord Forum

Mongoose server, Vercel deployment error

Unanswered
Alligator mississippiensis posted this in #help-forum
Open in Discord
Alligator mississippiensisOP
I am using mongoose for mongodb. Authentication works fine in localhost, except on deployments.. pLease help.

4 Replies

Alligator mississippiensisOP
// server-helper.ts

import mongoose from "mongoose";

const connect = async () => {
    if(mongoose.connections[0].readyState){
        return;
    }
    try {
        await mongoose.connect(process.env.DATABASE_URL!);
        console.log("Mongo connection successfully established")
    } catch(err){
                throw new Error("Error occured while connecting mongodb");
    }
}

export default connect;
// api/register/route.ts 

import connect from '@/utils/server-helper';
import Users from '@/models/Users';
import {NextResponse} from 'next/server'
import bcrypt from 'bcrypt';

export const POST = async(req: Request)=>{
    const{name,email,password} = await req.json();
    await connect();
    const existingUser = await Users.findOne({email})
    
    if(existingUser) { //if there is an existing user with the same email
        return new NextResponse("Email is already in use", {status:400}) //throw a Next.js Response with an error
    }
    
    const hashedPassword = await bcrypt.hash(password,10) // hashing user password before actually sending it to the database
    if(!name || !email || !password) {
        return NextResponse.json({message:"Invalid Data"}, {status:422})
    }
    
    const newUser = new Users({
        name,
        email,
        password: hashedPassword,
    })
    try {
        await newUser.save();
        return NextResponse.json("User is registered",{status:200})
        
    } catch (error) {
        console.log(error)

        return NextResponse.json({message: "Server error"},{status:500})

    }
    
}
this is the url path after I click any signin buttons ( including oauth providers) :

https://example.vercel.app/api/auth/error?error=Error%20occured%20while%20connecting%20mongodb
I don't understand why I can't access mongoose server