Vite on Vercel

Learn how to use Vercel's features with Vite.
Table of Contents

Vite is an opinionated build tool that aims to provide a faster and leaner development experience for modern web projects. Vite provides a dev server with rich feature enhancements such as pre-bundling NPM dependencies and hot module replacement, and a build command that bundles your code and outputs optimized static assets for production.

These features make Vite more desirable than out-of-the-box CLIs when building larger projects with frameworks for many developers.

Vite powers popular frameworks like SvelteKit, and is often used in large projects built with Vue, Svelte, React, Preact, and more.

To get started with Vite on Vercel:

  • If you already have a project with Vite, install Vercel CLI and run the vercel command from your project's root directory
  • Clone one of our Vite example repos to your favorite git provider and deploy it on Vercel with the button below:

Vercel deployments can integrate with your git provider to generate preview URLs for each pull request you make to your Vite project.

Although Vite offers modern features like SSR and Serverless Functions out of the box, implementing those features can sometimes require complex configuration steps. Because of this, many Vite users prefer to use popular community plugins.

Vite's plugins are based on Rollup's plugin interface, giving Vite users access to many tools from the Rollup ecosystem as well as the Vite-specific ecosystem.

We recommend using Vite plugins to configure your project when possible.

vite-plugin-vercel is a popular community Vite plugin that implements the Build Output API spec. It enables your Vite apps to use the following Vercel features:

When using the Vercel CLI, set the port as an environment variable. To allow Vite to access this, include the environment variable in your vite.config file:

vite.config.ts
import { defineConfig } from 'vite';
import vercel from 'vite-plugin-vercel';
 
export default defineConfig({
  server: {
    port: process.env.PORT as unknown as number,
  },
  plugins: [vercel()],
});

vite-plugin-ssr is another popular community Vite plugin that implements the Build Output API spec. It enables your Vite apps to do the following:

Vercel provides a set of System Environment Variables that our platform automatically populates. For example, the VERCEL_GIT_PROVIDER variable exposes the Git provider that triggered your project's deployment on Vercel.

These environment variables will be available to your project automatically, and you can enable or disable them in your project settings on Vercel. See our Environment Variables docs to learn how.

To access Vercel's System Environment Variables in Vite during the build process, prefix the variable name with VITE. For example, VITE_VERCEL_ENV will return preview, production, or development depending on which environment the app is running in.

The following example demonstrates a Vite config file that sets VITE_VERCEL_ENV as a global constant available throughout the app:

vite.config.ts
export default defineConfig(() => {
  return {
    define: {
      __APP_ENV__: process.env.VITE_VERCEL_ENV,
    },
  };
});

If you want to read environment variables from a .env file, additional configuration is required. See the Vite config docs to learn more.

To summarize, the benefits of using System Environment Variables with Vite on Vercel include:

  • Access to Vercel deployment information, dynamically or statically, with our preconfigured System Environment Variables
  • Access to automatically-configured environment variables provided by integrations for your preferred services
  • Searching and filtering environment variables by name and environment in Vercel's dashboard

Learn more about System Environment Variables

Edge Functions are a fast, scalable solution for delivering dynamic content to users. By default, Edge Functions are deployed globally, and will be invoked in one of Vercel's datacenters near your site's visitors.

Edge Functions are ideal when you need to interact with data over the network as fast as possible, such as executing OAuth callbacks, responding to webhook requests, or interacting with an API that fails if a request is not completed within a short time limit.

If your project uses a Vite community plugin, such as vite-plugin-ssr, you should follow that plugin's documentation for using Edge Functions.

If you're using a framework built on Vite, check that framework's official documentation or our dedicated framework docs. Some frameworks built on Vite, such as SvelteKit, support Edge Functions natively. We recommend using that framework's method for implementing Edge Functions.

If you're not using a framework or plugin that supports Edge Functions, you can still use them in your project by creating route modules in an api directory at the root of your project.

The following example demonstrates a basic api/handler Edge Function route:

api/handler.ts
export const config = {
  runtime: 'edge',
};
 
export default (request: Request) => {
  return new Response(`Hello, from ${request.url} I'm now an Edge Function!`);
};

You can test your Edge Function routes locally using Vercel CLI with the vercel dev command.

See our Function comparison table to understand whether Edge or Serverless is best for your use-case.

To summarize, Edge Functions with Vite on Vercel:

  • Offer cost savings by using fewer resources than Serverless Functions
  • Can execute in the region nearest to your users or nearest to data sources they depend on, based on your configuration
  • Have access to the geolocation and IP address of visitors, enabling location-based personalization

Learn more about Edge Functions

Serverless Functions scale up and down their resource consumption based on traffic demands. This scaling prevents them from failing during peak hours, but keeps them from running up high costs during periods of low activity.

If your project uses a Vite community plugin, such as vite-plugin-ssr, you should follow that plugin's documentation for using Serverless Functions.

If you're using a framework built on Vite, check that framework's official documentation or our dedicated framework docs. Some frameworks built on Vite, such as SvelteKit, support Serverless Functions natively. We recommend using that framework's method for implementing Serverless Functions.

If you're not using a framework or plugin that supports Serverless Functions, you can still use them in your project by creating routes in an api directory at the root of your project.

See our Edge Functions section to learn how to deploy your routes as Edge Functions instead.

The following example demonstrates a basic Serverless Function defined in an api directory:

api/handler.ts
import type { VercelRequest, VercelResponse } from '@vercel/node';
 
export default function handler(
  request: VercelRequest,
  response: VercelResponse,
) {
  response.status(200).json({
    body: request.body,
    query: request.query,
    cookies: request.cookies,
  });
}

See our Function comparison table to understand whether Edge or Serverless is best for your use-case.

To summarize, Serverless Functions on Vercel:

  • Scales to zero when not in use
  • Scales automatically with traffic increases
  • Support standard Web APIs, such as URLPattern, Response, and more

Learn more about Serverless Functions

Server-Side Rendering (SSR) allows you to render pages dynamically on the server. This is useful for pages where the rendered data needs to be unique on every request. For example, checking authentication or looking at the location of an incoming request.

Vite exposes a low-level API for implementing SSR, but in most cases, we recommend using a Vite community plugin.

See the SSR section of Vite's plugin repo for a more comprehensive list of SSR plugins.

To summarize, SSR with Vite on Vercel:

  • Scales to zero when not in use
  • Scales automatically with traffic increases
  • Has zero-configuration support for Cache-Control headers, including stale-while-revalidate

Learn more about SSR

If your Vite app is configured to deploy as a Single Page Application (SPA), deep linking won't work out of the box.

To enable deep linking in SPA Vite apps, create a vercel.json file at the root of your project, and add the following code:

vercel.json
{
  "rewrites": [
    {
      "source": "/(.*)",
      "destination": "/index.html"
    }
  ]
}

Deploying your app in Multi-Page App mode is recommended for production builds.

Learn more about Mutli-Page App mode in the Vite docs.

See our Frameworks documentation page to learn about the benefits available to all frameworks when you deploy on Vercel.

Learn more about deploying Vite projects on Vercel with the following resources:

Last updated on October 6, 2024