Issue
I’am trying to deploy my backend mern app in vercel and it shows me this error :
"404: NOT_FOUND
Code: NOT_FOUND
ID: cdg1::bbhc7-1691147707623-efc5cd10ff98
Here is my server.js file:
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const SocketServer = require("./socketServer");
const app = express();
app.use(express.json());
app.use(cors());
app.use(cookieParser());
// Socket
const http = require('http').createServer(app);
const io = require("socket.io")(http);
io.on("connection", socket => {
SocketServer(socket);
});
app.use("/api", require('./routes/authRouter'));
app.use("/api", require('./routes/userRouter'));
app.use("/api", require('./routes/postRouter'));
app.use("/api", require('./routes/commentRouter'));
const URI = process.env.MONGODB_URL;
mongoose
.connect(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected successfully to MongoDB");
})
.catch((err) => {
console.error("Error connecting to MongoDB", err);
});
const port = process.env.PORT || 5000;
http.listen(port, () => {
console.log("Server is running on port: ", port);
});
And here is my backend’s package.json:
"scripts": {
"dev": "nodemon server.js"
},
Solution
In order for Vercel to turn Express into a serverless function, you have to export the Express instance for Vercel’s build process.
add this at the end of the file server.js
:
module.exports = app;
After exporting Express, we have to tell Vercel what files to build, how to build them, and how to route them using a vercel.json file. So create vercel.json
. Then, specify your server.js
file and the NPM module Vercel will use to turn it into a serverless function:
{
"version": 2, // Vercel version
"builds": [
{
// Specify file to convert to a serverless function
"src": "server.js",
// Specify the NPM module that is used for the build
"use": "@vercel/node"
}
]
}
specify which paths will route to the server.js
file’s built serverless function using regex.
{
"version": 2,
"builds": [
{
"src": "server.js",
"use": "@vercel/node"
}
],
"routes": [
{
// Specify which paths will route to a destination using a regex
"src": "/(.*)",
// Specify the paths' destination
"dest": "server.js"
}
]
}
Finally, deploy your app
source: https://shadowsmith.com/thoughts/how-to-deploy-an-express-api-to-vercel
Answered By – Husain Mohamedi
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0