Build utilities for Vercel platform builders and serverless functions, providing utilities for creating and managing Lambda functions, file operations, and build-time helpers for the Vercel deployment platform
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Helper functions for Vercel platform integration, environment variable handling, runtime detection, and build optimization utilities.
Checks if a runtime name matches an official Vercel runtime, supporting both modern @vercel and legacy @now prefixes.
/**
* Checks if runtime is official Vercel runtime
* @param desired - Desired runtime name (without prefix)
* @param name - Full runtime name to check
* @returns True if name matches official runtime pattern
*/
function isOfficialRuntime(desired: string, name?: string): boolean;Usage Examples:
import { isOfficialRuntime } from "@vercel/build-utils";
// Check Node.js runtime
console.log(isOfficialRuntime("node", "@vercel/node")); // true
console.log(isOfficialRuntime("node", "@now/node")); // true (legacy)
console.log(isOfficialRuntime("node", "@vercel/node@1.0.0")); // true
console.log(isOfficialRuntime("node", "custom-node")); // false
// Check static runtime
console.log(isOfficialRuntime("static", "@vercel/static")); // true
console.log(isOfficialRuntime("static", "@now/static")); // true
// Check Python runtime
console.log(isOfficialRuntime("python", "@vercel/python")); // true
console.log(isOfficialRuntime("python", "@vercel/python@2.0.0")); // trueChecks if a runtime name represents the static file runtime.
/**
* Checks if runtime is static
* @param name - Runtime name to check
* @returns True if runtime is static
*/
function isStaticRuntime(name?: string): boolean;Usage Examples:
import { isStaticRuntime } from "@vercel/build-utils";
console.log(isStaticRuntime("@vercel/static")); // true
console.log(isStaticRuntime("@now/static")); // true
console.log(isStaticRuntime("@vercel/node")); // false
console.log(isStaticRuntime("custom-runtime")); // falseGets platform environment variables with support for both modern VERCEL_ and legacy NOW_ prefixes, ensuring no conflicts exist.
/**
* Gets platform environment variable with legacy support
* @param name - Environment variable name (without prefix)
* @returns Environment variable value or undefined
* @throws NowBuildError if both VERCEL_ and NOW_ variants are defined
*/
function getPlatformEnv(name: string): string | undefined;Usage Examples:
import { getPlatformEnv } from "@vercel/build-utils";
// Get deployment URL (checks VERCEL_URL first, then NOW_URL)
const deploymentUrl = getPlatformEnv("URL");
console.log(`Deployment URL: ${deploymentUrl}`);
// Get region (checks VERCEL_REGION first, then NOW_REGION)
const region = getPlatformEnv("REGION");
console.log(`Region: ${region}`);
// Get Git information
const gitCommitSha = getPlatformEnv("GIT_COMMIT_SHA");
const gitBranch = getPlatformEnv("GIT_COMMIT_REF");
// Use in build configuration
const config = {
deploymentUrl: getPlatformEnv("URL"),
environment: getPlatformEnv("ENV") || "production",
region: getPlatformEnv("REGION") || "iad1"
};
// Handle conflicts (throws error if both exist)
try {
const url = getPlatformEnv("URL");
} catch (error) {
console.error("Environment variable conflict:", error.message);
// Error: Both "VERCEL_URL" and "NOW_URL" env vars are defined
}Gets the latest supported Node.js version for the platform.
/**
* Gets latest supported Node.js version
* @returns Promise resolving to latest Node version info
*/
function getLatestNodeVersion(): Promise<NodeVersion>;
interface NodeVersion {
major: number;
range: string;
runtime: string;
discontinueDate?: Date;
}Usage Examples:
import { getLatestNodeVersion } from "@vercel/build-utils";
// Get latest Node.js version
const latestNode = await getLatestNodeVersion();
console.log(`Latest Node.js: ${latestNode.runtime} (${latestNode.range})`);
console.log(`Major version: ${latestNode.major}`);
// Use in build configuration
const buildConfig = {
runtime: latestNode.runtime,
nodeVersion: latestNode.range
};Gets list of discontinued Node.js versions that should not be used.
/**
* Gets list of discontinued Node.js versions
* @returns Promise resolving to array of discontinued versions
*/
function getDiscontinuedNodeVersions(): Promise<NodeVersion[]>;Usage Examples:
import { getDiscontinuedNodeVersions } from "@vercel/build-utils";
// Check for discontinued versions
const discontinued = await getDiscontinuedNodeVersions();
for (const version of discontinued) {
console.warn(`Node.js ${version.runtime} discontinued on ${version.discontinueDate}`);
}
// Validate Node.js version
function validateNodeVersion(requestedVersion: string) {
const isDiscontinued = discontinued.some(
v => v.runtime === requestedVersion
);
if (isDiscontinued) {
console.warn(`Warning: Node.js ${requestedVersion} is discontinued`);
}
}Determines if a request should be served by a specific entrypoint.
/**
* Determines if request should be served
* @param options - Request serving options
* @returns Promise resolving to true if should serve
*/
function shouldServe(options: ShouldServeOptions): Promise<boolean>;
interface ShouldServeOptions {
requestPath: string;
entrypoint: string;
files: {
[path: string]: FileFsRef;
};
workPath: string;
config: Config;
}Usage Examples:
import { shouldServe, FileFsRef } from "@vercel/build-utils";
// Check if API route should handle request
const files = {
"api/users.js": await FileFsRef.fromFsPath({ fsPath: "/project/api/users.js" })
};
const shouldHandle = await shouldServe({
requestPath: "/api/users/123",
entrypoint: "api/users.js",
files,
workPath: "/tmp/build",
config: {}
});
if (shouldHandle) {
console.log("This entrypoint should handle the request");
}
// Check static file serving
const staticFiles = {
"public/index.html": await FileFsRef.fromFsPath({ fsPath: "/project/public/index.html" })
};
const shouldServeStatic = await shouldServe({
requestPath: "/",
entrypoint: "public/index.html",
files: staticFiles,
workPath: "/tmp/build",
config: { cleanUrls: true }
});Debug logging utility with namespace support.
/**
* Creates debug logger
* @param namespace - Debug namespace
* @returns Debug function
*/
function debug(namespace: string): (message: string, ...args: any[]) => void;
// Default debug instance
const debug: (message: string, ...args: any[]) => void;Usage Examples:
import { debug } from "@vercel/build-utils";
// Use default debug
debug("Starting build process");
debug("Processing %d files", fileCount);
// Create namespaced debugger
const debugBuilder = debug("builder");
debugBuilder("Detected framework: %s", framework.name);
debugBuilder("Build command: %s", buildCommand);
// Enable debug output with environment variable
// DEBUG=@vercel/build-utils:* npm run buildCustom error class for build-related errors with structured information.
/**
* Custom error class for build errors
*/
class NowBuildError extends Error {
hideStackTrace: boolean;
code: string;
link?: string;
action?: string;
constructor(options: NowBuildErrorOptions);
}
interface NowBuildErrorOptions {
message: string;
code: string;
link?: string;
action?: string;
}Usage Examples:
import { NowBuildError } from "@vercel/build-utils";
// Throw structured error
throw new NowBuildError({
code: "MISSING_PACKAGE_JSON",
message: "package.json not found in project root",
link: "https://vercel.com/docs/concepts/projects/overview",
action: "Add package.json"
});
// Handle build errors
try {
// Build operation
} catch (error) {
if (error instanceof NowBuildError) {
console.error(`Build Error [${error.code}]: ${error.message}`);
if (error.link) {
console.error(`Documentation: ${error.link}`);
}
if (error.action) {
console.error(`Suggested action: ${error.action}`);
}
}
}Formats validation errors into user-friendly NowBuildError instances.
/**
* Formats validation errors nicely
* @param obj - Error object from validation
* @returns Formatted NowBuildError
*/
function getPrettyError(obj: {
dataPath?: string;
message?: string;
params: any;
}): NowBuildError;Usage Examples:
import { getPrettyError } from "@vercel/build-utils";
// Format validation error
const validationError = {
dataPath: ".functions.api",
message: "should NOT have additional property",
params: { additionalProperty: "invalidProperty" }
};
const prettyError = getPrettyError(validationError);
console.error(prettyError.message);
// Output: `.functions.api` should NOT have additional property `invalidProperty`. Please remove it.Platform environment variables accessible via getPlatformEnv():
URL - Deployment URLENV - Environment (production, preview, development)REGION - Deployment regionGIT_COMMIT_SHA - Git commit SHAGIT_COMMIT_REF - Git branch or tagGIT_COMMIT_MESSAGE - Commit messageGIT_REPO_SLUG - Repository slugGIT_REPO_OWNER - Repository ownerBUILD_ID - Unique build identifierDEPLOYMENT_ID - Deployment identifierThe runtime detection functions help identify official Vercel runtimes:
import { isOfficialRuntime, isStaticRuntime } from "@vercel/build-utils";
function configureBuilder(runtimeName: string) {
if (isStaticRuntime(runtimeName)) {
return { type: "static", buildCommand: null };
}
if (isOfficialRuntime("node", runtimeName)) {
return { type: "serverless", runtime: "nodejs18.x" };
}
if (isOfficialRuntime("python", runtimeName)) {
return { type: "serverless", runtime: "python3.9" };
}
// Custom runtime
return { type: "custom", runtime: runtimeName };
}Install with Tessl CLI
npx tessl i tessl/npm-vercel--build-utils