Vercel is a hosting service for web development. This also provides us some functions which are able to be used as a server.
This post is about how to deploy a simple echo server with TypeScript. The code is here.
Install required modules.
The libraries are typescript and @vercel/node.
npm i -D typescript @vercel/node
@vercel/node
provides me typing to use typescript on vercel. Vercel functions endopoint require us some kind of rules. We must obey the rule and typings.
Write functions
import { NowRequest, NowResponse } from "@vercel/node";
// request -> ?id={your_id}
export default async (req: NowRequest, res: NowResponse) => {
const { query } = req;
const { id } = query;
res.json({ id });
};
req and res is typed by @vercel/node.
Put the code to api/
If you put the code into /api/
, vercel serve this as a serverless function endpoint.
The point is the directory is not /pages/api/
. If you know NextJS, you know Next.js treats /pages/api
as serverless functions endpoint. This endpoint is called "API Routes" as Next.js's term.
Sometimes "Vercel Serverless Functions" and "API Routes" are confused. Because those have the same feature but the usage is different.
Now we only use Vercel Serverless Function, so we just put this file to /api/
Deploy
Push to GitHub and connect the repository to Vercel. After that, access "*.vercel.app/api/${function_name}?id=hoge", you will get response 'hoge'.
Top comments (0)