Deploying your Node.js backend on Vercel is a streamlined process that can bring your application to life on the web. In this revised guide, we'll walk you through the updated steps to ensure your backend is deployed using the most current methods. Let's get started.
1. Create Your Vercel Account
To begin, sign up for a Vercel account at vercel.com . You can choose your preferred authentication method, whether it's GitHub, GitLab, or Bitbucket.
2. Create a Simple Express API
Ensure you have Node.js and NPM installed on your local machine. If not, you can download them from https://nodejs.org/.
Start by creating a new directory for your project, navigating to it, and initializing a new Node.js project:
mkdir my-express-api
cd my-express-api
npm init -y
Install Express and create an index.js
file :
npm install express
touch index.js
Open index.js
in your preferred code editor and add the following code to create a basic Express API:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Express on Vercel");
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
3. Export the Express API
Modify your index.js
file to export the Express app at the end of the file:
// ... (previous code)
module.exports = app; // Export the Express app
4. Add vercel.json
Configuration
Create a vercel.json
file in your project directory:
touch vercel.json
```Inside `` `vercel.json `` , specify the build settings and routes as follows:
```js
{
"version": 2,
"builds": [
{
"src": "index.js",
"use": "@now/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "index.js"
}
]
}
5. Deploy Your Express API
Initialize a Git repository, commit your code, and push it to your source repository, whether it's on GitHub, GitLab, or another platform.
- Vercel will automatically detect your repository and build your Express API based on the
vercel.json
configuration.
Once the deployment is complete, you can access your API at the provided Vercel URL, such as your-app-name.vercel.app
, to confirm that it's up and running.
Congratulations! Your Node.js backend is now successfully deployed on Vercel as a serverless function. Be sure to adapt this guide to your specific project structure and requirements for a seamless deployment experience.