In this quickstart guide, you'll learn how to get started with Serverless Functions on Vercel using Vercel CLI. The guide will cover:
- Creating a Serverless Function
- Deploying a Serverless Function with Vercel CLI
You should have the latest version of Vercel CLI installed. To check your version, use
vercel --version
. To install or update Vercel CLI, use:pnpm i -g vercel@latest
You should have an existing project. If you don't have one, you can run the following terminal command to create a Next project:
terminalnpx create-next-app@latest --typescript
Select your preferred framework to get started. The implementation of the Serverless Function will differ depending on the framework you choose.
In the app
directory:
Create /api/serverless-example/route.ts
Then, add the following code, which will return the body
, path
query
, and cookies
from the request object as JSON:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function GET(request: NextRequest) {
return NextResponse.json(
{
body: request.body,
path: request.nextUrl.pathname,
query: request.nextUrl.search,
cookies: request.cookies.getAll(),
},
{
status: 200,
},
);
}
Use next dev
to start a local development server:
next dev
Navigate to http://localhost:3000/api/serverless-example?query=123 to see the response from your route.
You should see a response similar to the following:
{
body: null,
path: "/api/serverless-example",
query: "?query=123",
cookies: [
...
],
};
Was this helpful?