How To Build And Deploy A Node API On Vercel Serverless functions
Deploy Your REST API In Less Than 10 Minutes!
Vercel Serverless Functions
Vercel, the company behind Next.js and the SWR fetching library, has a nice serverless offering. Vercel is also well known for great DX and quick zero configuration deployments. These deployments open the door to really fast project setup and going to production easily.
In this tutorial you will cover how to set up a Typescript REST API using Vercel Serverless Functions with minimal overhead.
Table Of Content
Setting Up
- First, install the Vercel CLI and log in. Be sure you have an account at Vercel.
yarn global add vercel
vercel login
- The login step will require you to enter your email and follow the instructions. Make sure you complete the instructions and then create a new project.
mkdir vercel-api
cd vercel-api
yarn init -y
mkdir api
Let's add the only dev dependency to run our project locally.
yarn add vercel -D
- Once this is done, open the project folder in your favorite editor and open
package.json
. We will need to add a script section to have a proper dev environment. You will need a script for deploying and a script for starting the dev server. Your file should look like this.
{
"name": "vercel-api",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "vercel dev",
"deploy": "vercel deploy --prod"
},
"devDependencies": {
"vercel": "^28.4.10"
}
}
The last step before running the project locally is to connect it to the Vercel dashboard.
- From the root of the project run
vercel
and accept all the default parameters.
We are using Vercel's zero configs set up. The project will be uploaded the first time but will not contain any endpoints.
We now need to create our first endpoint.
Create the
api/index.ts
file. Vercel will define your API routes based on your folder and file structure and look under each folder or file for a default export. Vercel will then create a corresponding serverless function to handle the route.Now, let's add the following code to our base API route in
api/index.ts
import { VercelRequest, VercelResponse } from "@vercel/node";
export default (req: VercelRequest, res: VercelResponse) => {
return res.json({ message: "Hello World" });
};
We could alternatively use the the newer Edge Runtime. This runtime is a smaller but much faster runtime. It is also a bit more limited in terms of what you can do. For example, you cannot use the fs
module. To use that runtime, our function would look like this in api/index.ts
.
export const config = {
runtime: "experimental-edge",
};
export default (req) =>
new Response(`Hello, from ${req.url} I'm now an Edge Function!`);
- Run the project using:
yarn start
- You will be prompted to first link the project to your Vercel account. Here are the different prompts:
- Set up and develop “vercel-api” [Y/n]: select y
- Which scope should contain your project?: select your account
- Link to existing project? [y/N]: n
- What’s your project’s name?: use the default `vercel-api` or change it to your liking
- In which directory is your code located?: select the default `.`
- Want to modify these settings? [y/N]: n
This will start a local development server on http://localhost:3000/api.
Navigating to this first endpoint will give you a "Hello World" message.
Now let's go ahead and add a dynamic route using query parameters. Vercel Serverless Function handles dynamic routes in a similar way to Next.js. You can use the [paramName].ts
syntax to define the name of the query parameter.
- Create a user folder and id route to see this in action:
mkdir api/users
touch "api/users/[id].ts"
- In your
api/users/[id].ts
file, add the following code.
import { VercelRequest, VercelResponse } from "@vercel/node";
const users = ["Bob Smith", "Guillaume Bibeau"];
export default (req: VercelRequest, res: VercelResponse) => {
const { id } = req.query;
res.status(200).json({ user: users[Number(id)] });
};
You can access the query parameter under the req.query
object made available to the handler. Navigating or sending a request to http://localhost:3000/api/users/0
should now give you the corresponding user from the users
array: {user: "Bob Smith"}
.
Deploying
Now that you have the basic folder structure and code of your API, you can proceed and deploy the API on Vercel's cloud platform.
One interesting thing to note before proceeding is that Vercel lets us use Typescript without even needing to compile in Webpack or having to configure anything. While you might want your own tsconfig.json
for production projects, it is interesting to get a prototype API online quickly! Now let's deploy all of this:
yarn deploy
The Vercel CLI will proceed to build all the necessary Serverless Functions bundles and you can just sit while the magic happens. After a couple of seconds, you should be prompted with the deployed URL to your service. To test it out navigate to the URL and add then to /api/users/0
. You should get the same results as the development server.
Conclusion
Getting an API project started with Vercel Serverless functions is convenient and really fast. Here are some takeaways:
- Vercel takes zero configurations and is able to run your project.
- You can start using Typescript, Javascript or any supported languages.
- The repo code is here Github.
Send any questions or comments at g.bibeaulaviolette@gmail.com!