This gist would offer a step-by-step guide of some sort for quickly setting
up a "serverless" API using expressjs, and Vercel's Now platform for local
development with now dev
and eventual prod deployment now --prod
If you haven't already, install now's cli tool globally on your development environment:
npm i -g now
To confirm if you have it installed, run:
now --version
You should get something similar to this:
Your specific version may vary depending on the latest version on the date you are reading this, but that shouldn't cause any hiccups (I hope).
If you don't have one already, set up a Vercel account on their site, and
authenticate locally by running now login
on your terminal.
Following the prompts should authenticate you correctly.
With installation and auth out of the way, we can now set up individual projects for
local development using now dev
and even prod deployments.
Using an express boilerplate, let's set up one project. Here's the entire boilerplate structure:
├── .gitignore
├── index.js
├── now.json
└── package.json
Here's .gitignore
:
node_modules/
Here's index.js
:
const express = require('express');
const app = express();
app.get('/api/', (req, res) => {
res.send({ message: '=)' });
});
app.all('*', (req, res) => {
res.status(404).send({ message: 'route not defined!' });
});
module.exports = app;
Here's now.json
:
{
"version": 2,
"builds": [{ "src": "index.js", "use": "@now/node" }],
"routes": [{ "src": "/(.*)", "dest": "index.js" }]
}
Finally, here's package.json
:
{
"name": "express-vercel",
"version": "0.1.0",
"description": "express vercel boilerplate",
"main": "index.js",
"scripts": {
"dev": "now dev"
},
"dependencies": {
"express": "^4.17.1"
},
"keywords": [
"vercel"
],
"author": "Kizito Akhilome",
"license": "MIT"
}
To get started, let's install project dependencies (npm i
):
For us to be able to use the now dev
command for the project,
we must first connect the project to our Vercel account by simply running
now
from the project's root directory. Like so:
Following and answering the prompts should get us setup:
With connecting done, we can now conveniently startup the dev server by running now dev
:
And test out the API by hitting localhost:3000/api/
:
To conveniently deploy to prod, now --prod
would do the trick: