Vercel is a fantastic cloud platform that stands out from the crowd by its simplicity and excellent developer experience. One reason for its success is the intense focus on full-stack Javascript web apps. However, that doesn't mean you can't deploy a headless service on Vercel.
In this post, let's have fun building a secure database-centric RESTful API with Express.js, Prisma, and ZenStack, and deploying it onto Vercel. We'll also leverage the new Vercel Postgres offering for data persistence.
Scenarioโ
We're going to build a very simple Pet Store service here. Its API will have the following resources:
- User: who can signup, login, and order pets.
- Pet: which can be listed and ordered by users.
- Order: which is created by users and contains a list of pets.
Business rules:
- Anonymous users can sign up and log in.
- Anonymous users can list unsold pets.
- Authenticated users can list unsold pets and pets ordered by them.
- Authenticated users can create orders for unsold pets.
- Authenticated users can view their orders.
You can find the finished project here.
Building The Serviceโ
The primary reference documentation that guides us through the process is Using Express.js with Vercel.
1. Creating the projectโ
Let's first create a new Express.js project with Typescript support.
mkdir vercel-petstore
cd vercel-petstore
npm init -y
npm install express
npm install -D typescript tsx @types/node @types/express
npx tsc --init
Create the serverless function entry point (as required by Vercel) /api/index.ts
with the following content:
import express from 'express';
const app = express();
// enable JSON body parser
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello World!');
});
export default app;
Then create /api/app.ts
for launching the Express server and testing it locally:
import app from '.';
app.listen(3000, () => console.log('๐ Server ready at: http://localhost:3000'));
Start the server:
npx tsx watch api/app.ts
Now in a new shell window, hit the service endpoint and verify it works:
curl localhost:3000
Hello World!