Skip to content
12 min read

Astro on Vercel

Learn how to use Vercel's features with Astro

Astro is an all-in-one web framework that enables you to build performant static websites. People choose Astro when they want to build content-rich experiences with as little JavaScript as possible.

There are multiple ways to get started with Astro on Vercel:

  • If you already have a project with Astro, install Vercel CLI and run the vercel command from your project's root directory
  • Clone one of our Astro 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 Astro project.

You can also use Astro in our Edge Runtime with our Astro at the Edge example project.

You can deploy a static Astro site to Vercel with zero configuration using our framework preset. To use many of Vercel's features, you must deploy your site using SSR. The recommended way to do this is with Astro's Vercel adapter.

The following steps will guide you through configuring the Vercel adapter in your Astro project.

You can add the Vercel adapter to your Astro project by running the following command:

pnpm
yarn
npm
pnpm astro add vercel

Alternatively, you can add the Vercel adapter to your Astro project manually by installing it with your favorite package manager as demonstrated below:

pnpm
yarn
npm
pnpm i @astrojs/vercel

Finally, edit your astro.config.mjs file to specify that you want your output to be rendered on the server, and you want to deploy your app as an Edge Function, Serverless Function, or static content.

The following code sample demonstrates a valid astro.config.mjs for all three options. Use the tabs to swap between Edge, Serverless and static.

astro.config.mjs
import { defineConfig } from 'astro/config';
import vercelEdge from '@astrojs/vercel/edge';
 
export default defineConfig({
  output: 'server',
  adapter: vercelEdge(),
});
Astro's Image Optimization is only available for static and Serverless deployments. Edge support is yet to be implemented.

You can also specify files that should be included or excluded from your Edge or Serverless Functions in your project's astro.config.mjs. Learn more in Astro's docs on the Vercel adapter.

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, verifying authentication or checking the geolocation of an incoming request.

Vercel offers SSR that scales down resource consumption when traffic is low, and scales up with traffic surges. This protects your site from accruing costs during periods of no traffic or losing business during high-traffic periods.

Enabling SSR for your Astro project allows you to use Edge and Serverless Functions with Vercel. This allows you to add dynamic elements to your app, such as user logins and personalized content.

Enable SSR by adding output: 'server' to your project's defineConfig object and installing the Vercel adapter. The following is an example of an astro.config.mjs file that enables Serverless SSR with the Vercel adapter.

astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';
 
export default defineConfig({
  output: 'server',
  adapter: vercel(),
});

To summarize, SSR with Astro 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
  • Framework-aware infrastructure enables switching rendering between Edge/Node.js runtimes

Learn more about SSR

Deploying your Astro site to Vercel with SSR on either our Edge or Node.js serverless runtimes allows you to respond to requests dynamically at scale. The Node.js serverless runtime grants you a Node.js environment with enough compute power for complex tasks, while Edge grants you a limited environment with low latency.

You can use our Function Comparison table to decide which runtime is best for you. Edge Functions are generally faster than Serverless Functions when handling requests that require little processing power and rely on few or no databases. Serverless Functions are slower, but have more computational resources and full access to the Node.js API, which Edge Functions currently lack.

Serverless Functions may also be faster than Edge Functions for requests that rely on databases. See our docs on Regional Function Execution to learn more.

When you create an Astro page with a slug in brackets, such as [post] or [author], you can generate pages based on the value in the slug's position when a user visits a route.

For example, a page like posts/[post].astro can dynamically render a different post when a user visits your-site.com/posts/example-1 or your-site.com/posts/example-2.

src/pages/posts/[post].astro
---
const { post } = Astro.params;
---
<h1>{post}</h1>
<p>
  ... Other content here
</p>

Once you install Astro's Vercel adapter and configure your astro.config.mjs to use either Serverless or Edge, all routes in your site will be server-rendered on your chosen runtime by default.

Use the tabs below to see an example astro.config.mjs that use Server-Side Rendering in Vercel's Edge or Serverless runtime:

With your config file setup, you can use Astro's component script to get the route segments, and render content dynamically based on which path the user is visiting.

The following example renders an Astro page dynamically. If the user is visiting an unexpected path, it redirects them to a 404 page.

src/pages/[...slug].astro
---
const pages = [
  {
    slug: 'products',
    title: 'Astro products',
    text: 'We have lots of products for you',
  },
  {
    slug: 'products/astro-handbook',
    title: 'The ultimate Astro handbook',
    text: 'If you want to learn Astro, you must read this book.',
  }
];
 
const { slug } = Astro.params;
const page = pages.find((page) => page.slug === slug);
if (!page) return Astro.redirect("/404");
const { title, text } = page;
---
<html>
<head>
  <title>{title}</title>
</head>
<body>
  <h1>{title}</h1>
  <p>{text}</p>
</body>
</html>

You can also create Edge or Serverless Functions by creating a /api directory in your project's root directory.

The following is an example of a basic Edge Function:

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!`);
};

To learn more, see our:

To summarize, Edge Functions with Astro 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

Astro does not support route-specific middleware. Instead, you can create a single global middleware.ts file, which will run before every request.

To limit the code in your middleware.ts module to specific routes, you can export a config object with the matcher property, which allows you to specify which paths the middleware should apply to. You can set the value of the matcher to a plain string, or a string containing regex.

The following is an example of a middleware.ts file that matches the /admin path and redirects to a path called /redirected.

middleware.ts
export const config = {
  // Only run the middleware on the admin route
  matcher: '/admin',
};
 
export default function middleware(request: Request): Response {
  const url = new URL(request.url);
 
  if (url.pathname === '/admin') {
    url.pathname = '/redirected';
  }
  return Response.redirect(url);
}

Learn more about matcher in our Middleware docs.

You can also configure your Astro site to run on either the Edge or Node.js serverless runtime, allowing you to use middleware with Edge or Serverless functions. Using matcher does not alter the runtime your API routes execute in. You cannot use matcher to deploy certain API routes in one runtime and others in another. Your chosen runtime applies to all API routes.

The Response your middleware function sends back to Astro is an instance of the Web Fetch API's Response interface. Learn more about Response objects in the MDN docs.

You can return a new Response() object with the information you want to send, or use the static methods redirect and error to redirect users or send an internal server error response through middleware.

The following is an example of a middleware.ts file that matches the /admin path and responds with a 404.

middleware.ts
export const config = {
  // Only run the middleware on the admin route
  matcher: '/admin',
};
 
export default function middleware(request: Request): Response {
  const url = new URL(request.url);
 
  if (url.pathname === '/admin') {
    url.pathname = '/redirected';
  }
  return new Response(null, {
    status: 404,
    statusText: 'Not found',
  });
}

You can test Middleware in your local environment with Vercel CLI. The vercel dev or vc dev commands add some helpers to your framework's standard dev equivalent command, extending it to let you also test Vercel features like Middleware and Serverless Functions.

Install Vercel CLI with the following terminal command:

pnpm
yarn
npm
pnpm i -g vercel

To summarize, Edge Middleware with Astro on Vercel:

  • Executes before a request is processed on a site, allowing you to modify responses to user requests
  • Runs on all requests, but can be scoped to specific paths through a matcher config
  • Uses our lightweight Edge Runtime to keep costs low and responses fast

Learn more about Edge Middleware

We do not recommend using vercel.json to rewrite URL paths with astro projects. At the moment, trying to rewrite a URL with vercel.json produces inconsistent behavior, and is not officially supported. Read our docs on Edge Middleware with Astro to learn how to execute redirects from Middleware instead.

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

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

Last updated on March 2, 2023