Using the Node.js Runtime with Vercel Functions
You can create Vercel Function in JavaScript or TypeScript by using the Node.js runtime. By default, the runtime builds and serves any function created within the/api
directory of a project to Vercel.
Node.js-powered functions are suited to computationally intense or large functions and provide benefits like:
- More RAM and CPU power: For computationally intense workloads, or functions that have bundles up to 250 MB in size, this runtime is ideal
- Complete Node.js compatibility: The Node.js runtime offers access to all Node.js APIs, making it a powerful tool for many applications
In order to use the Node.js runtime, create a file inside theapi
directory with a function using theWeb signature. No additional configuration is needed:
exportfunctionGET(request:Request) {returnnewResponse('Hello from Vercel!');}
Alternatively, a Node.js handler that takesthe standard Node.js Request and Response objects is as follows:
import { VercelRequest, VercelResponse }from'@vercel/node';exportdefaultfunctionhandler(req:VercelRequest, res:VercelResponse) {constname=req.query.name??'World';res.writeHead(200);res.write(`Hello${name}!`);res.end();}
To learn more about creating Vercel Functions, see theFunctions API Reference. If you need more advanced behavior, such as a custom build step or private npm modules, see theadvanced Node.js usage page.
The entry point forsrc
must be a glob matching.js
,.mjs
, or.ts
files** that export a default function.
Vercel Functions using the Node.js runtime supportall Node.js APIs, including standard Web APIs such as theRequest and Response Objects.
To learn more about the supported Node.js versions on Vercel, seeSupported Node.js Versions.
For dependencies listed in apackage.json
file at the root of a project, the following behavior is used:
- If
pnpm-lock.yaml
is present,pnpm install
is executed- Seesupported package managers for pnpm detection details
- If
package-lock.json
is present,npm install
is executed- If
"lockfileVersion": 2
is present in the lock file, npm 8 is used - Otherwise npm 6 is used
- If
- If
bun.lockb
orbun.lock
is present, the Install Command isbun install
- Bun 1 is used
- Otherwise,
yarn install
is executed
If you need to select a specific version of a package manager, seecorepack.
The Node.js runtime supports files ending with.ts
inside of the/api
directory as TypeScript files to compile and serve when deploying.
An example TypeScript file that exports a Web signature handler is as follows:
exportasyncfunctionGET(request:Request) {consturl=newURL(request.url);constname=url.searchParams.get('name')||'World';returnResponse.json({ message:`Hello${name}!` });}
You can use atsconfig.json
file at the root of your project to configure the TypeScript compiler. Most options are supported aside from"Path Mappings" and"Project References".
Each request to a Node.js Vercel Function gives access to Request and Response objects. These objects are thestandard HTTPRequest andResponse objects from Node.js.
Vercel additionally provides helper methods inside of the Request and Response objects passed to Node.js Vercel Functions. These methods are:
method | description | object |
---|---|---|
request.query | An object containing the request'squery string, or{} if the request does not have a query string. | Request |
request.cookies | An object containing the cookies sent by the request, or{} if the request contains no cookies. | Request |
request.body | An object containing the body sent by the request, ornull if no body is sent. | Request |
response.status(code) | A function to set the status code sent with the response wherecode must be a validHTTP status code. Returnsresponse for chaining. | Response |
response.send(body) | A function to set the content of the response wherebody can be astring , anobject or aBuffer . | Response |
response.json(obj) | A function to send a JSON response whereobj is the JSON object to send. | Response |
response.redirect(url) | A function to redirect to the URL derived from the specified path with status code "307 Temporary Redirect". | Response |
response.redirect(statusCode, url) | A function to redirect to the URL derived from the specified path, with specifiedHTTP status code. | Response |
The following Node.js Vercel Function example showcases the use ofrequest.query
,request.cookies
andrequest.body
helpers:
import { VercelRequest, VercelResponse }from"@vercel/node";module.exports= (request:VercelRequest, response:VercelResponse)=> {let who='anonymous';if (request.body&&request.body.who) { who=request.body.who; }elseif (request.query.who) { who=request.query.who; }elseif (request.cookies.who) { who=request.cookies.who; }response.status(200).send(`Hello${who}!`);};
Example Node.js Vercel Function using therequest.query
,request.cookies
,andrequest.body
helpers. It returns greetings for the user specified usingrequest.send()
.
If needed, you can opt-out of Vercel providinghelpers
usingadvancedconfiguration.
We populate therequest.body
property with a parsed version of the content sent with the request when possible.
We follow a set of rules on theContent-type
header sent by the request to do so:
Content-Type header | Value ofrequest.body |
---|---|
No header | undefined |
application/json | An object representing the parsed JSON sent by the request. |
application/x-www-form-urlencoded | An object representing the parsed data sent by with the request. |
text/plain | A string containing the text sent by the request. |
application/octet-stream | ABuffer containing the data sent by the request. |
With therequest.body
helper, you can build applications without extra dependencies or having to parse the content of the request manually.
Therequest.body
helper is set using aJavaScriptgetter.In turn, it is only computed when it is accessed.
When the request body contains malformed JSON, accessingrequest.body
will throw an error. You can catch that error by wrappingrequest.body
withtry...catch
:
try {request.body;}catch (error) {returnresponse.status(400).json({ error:'My custom 400 error' });}
Catching the error thrown byrequest.body
withtry...catch
.
Express.js is a popular framework used with Node.js. For information on how to use Express with Vercel, see the guide:Using Express.js with Vercel.
The Node.js runtime can be used as an experimental feature to run middleware. To enable, add the flag to yournext.config.ts
file:
importtype { NextConfig }from'next';constnextConfig:NextConfig= { experimental: { nodeMiddleware:true, },};exportdefault nextConfig;
Then in your middleware file, set the runtime tonodejs
in theconfig
object:
exportconstconfig= { matcher:'/about/:path*', runtime:'nodejs',};
Running middleware on the Node.js runtime incurs charges underVercelFunctions pricing. These functionsonly run usingFluid compute.
Was this helpful?