I hosted a Chat-App builded using Next JS that, Just having Authentication Right now, throwing an error syntax error: Unexpected end of JSON input
- In My localhost ( development server same code works fine )
- I even tried it through local host build server
When I hosted the app on Vercel , After setup the environment Variables properly and could see the error i mentioned above, Now I have no Ideas why its throwing an error if its fine in local host
Here is My Code
Services Page
export const register_user = async (formData) => {
try {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/auth/register`, {
method: 'POST',
body: formData,
})
const data = await res.json();
console.log(res)
return data
} catch (error) {
console.error('error in register_user: (Services) => ', error)
}
}
export const login_user = async (formData) => {
try {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
const data = await res.json()
console.log(res)
return data
} catch (error) {
console.error('error in login_user: (Services) => ', error)
}
}
export const reset_user_password = async (formData) => {
try {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/auth/resetPassword`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
const data = await res.json();
return data;
} catch (error) {
console.error('error in login_user: (Services) => ', error)
}
}
Backend Code
import ConnectDB from '@/DB/connectDB';
import User from '@/models/User';
import Joi from 'joi';
import { compare } from 'bcryptjs';
import jwt from 'jsonwebtoken';
const schema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().required(),
});
export default async (req, res) => {
await ConnectDB();
const { email, password } = req.body;
const { error } = schema.validate({ email, password });
if (error) return res.status(401).json({ success: false, message: error.details[0].message.replace(/['"]+/g, '') });
try {
const checkUser = await User.findOne({ email });
if (!checkUser) return res.status(401).json({ success: false, message: "Account not Found" });
const isMatch = await compare(password, checkUser.password);
if (!isMatch) return res.status(401).json({ success: false, message: "Incorrect Password" });
const token = jwt.sign({ id: checkUser._id, email: checkUser.email }, process.env.JWT_SECREAT, { expiresIn: '1d' });
const user = {name : checkUser.name , photo : checkUser.photo, _id : checkUser._id , email : checkUser.email}
const finalData = {token , user }
return res.status(200).json({ success: true, message: "Login Successfull", finalData})
} catch (error) {
console.log('Error in register (server) => ', error);
return res.status(500).json({ success: false, message: "Something Went Wrong Please Retry Later !" })
}
}