How to Deploy an Express API to Vercel π
Hey there! So, you've got this snazzy Express API and you're thinking, "Man, I wish this could be even faster and free!" Well, good news! You can deploy your Express API to Vercel as a serverless function, giving you a blazing fast CDN-served API for absolutely zero cost. Let's dive into it with some easy steps. π
Step 1: Create your Vercel Account π
First things first, head over to vercel.com and sign up using your GitHub, GitLab, or Bitbucket account. By doing this, Vercel will start looking for vercel.json
or now.json
files whenever you push changes to your projects. This magical process will link your project across services and set up a CI pipeline for you. This pipeline will handle the initial deployment and create Preview Deployments for every subsequent commit on every branch. Pretty neat, huh? π
Step 2: Create a Simple Express API (if you don't have one) π οΈ
Don't have an Express API yet? No worries! Let's quickly set one up. Make sure you have Node and npm installed, then follow these steps:
mkdir my-express-api
cd my-express-api
npm init -y
npm install express
Now, create an index.js
file and add this code to get things rolling:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.send("Express on Vercel π");
});
app.listen(5000, () => {
console.log("Running on port 5000.");
});
Step 3: Export the Express API βοΈ
For Vercel to work its magic and turn our Express app into a serverless function, we need to export the Express instance. Simply add this at the end of your index.js
file:
// Export the Express API
module.exports = app;
Step 4: Add vercel.json
Configuration π οΈ
Time to tell Vercel what's what. Create a vercel.json
file in your project's root directory:
touch vercel.json
Copy and paste this configuration into vercel.json
:
{
"version": 2,
"builds": [
{
"src": "index.js",
"use": "@now/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "index.js"
}
]
}
Step 5: Deploy your Express API π
Alrighty, everything's set up! Time to push your project to your source repository, and watch Vercel do its thing. Once the build process is complete, visit the .vercel.app
URL Vercel provides to see "Express on Vercel" in action! π
Conclusion π
So there you have it! Deploying your Express API to Vercel as a serverless function is a fantastic way to get a lightning-fast, CDN-served API without spending a dime. Remember, if you're starting from scratch, you can create APIs using exported functions in an api
directory as explained in the Vercel docs. This guide aims to simplify the process of preparing an Express API for deployment on Vercel, so you can say goodbye to slow or costly providers. Happy coding! π»β¨
Top comments (0)