astro/packages/integrations/vercel
Erika b76c166bdd
feat: unflag experimental.assets (#7921)
Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
Co-authored-by: Emanuele Stoppa <my.burning@gmail.com>
2023-08-16 10:21:05 +02:00
..
src feat: unflag experimental.assets (#7921) 2023-08-16 10:21:05 +02:00
test feat: unflag experimental.assets (#7921) 2023-08-16 10:21:05 +02:00
CHANGELOG.md Merge remote-tracking branch 'origin/main' into next 2023-08-15 09:24:06 +01:00
package.json [ci] release (beta) (#8067) 2023-08-14 08:46:22 -05:00
README.md Remove the Vercel Edge adapter (#8015) 2023-08-10 13:12:13 -04:00
tsconfig.json Remove support for Node 16 (#7780) 2023-08-08 11:01:33 +01:00

@astrojs/vercel

This adapter allows Astro to deploy your SSR site to Vercel.

Learn how to deploy your Astro site in our Vercel deployment guide.

Why Astro Vercel

If you're using Astro as a static site builder — its behavior out of the box — you don't need an adapter.

If you wish to use server-side rendering (SSR), Astro requires an adapter that matches your deployment runtime.

Vercel is a deployment platform that allows you to host your site by connecting directly to your GitHub repository. This adapter enhances the Astro build process to prepare your project for deployment through Vercel.

Installation

Add the Vercel adapter to enable SSR in your Astro project with the following astro add command. This will install the adapter and make the appropriate changes to your astro.config.mjs file in one step.

# Using NPM
npx astro add vercel
# Using Yarn
yarn astro add vercel
# Using PNPM
pnpm astro add vercel

If you prefer to install the adapter manually instead, complete the following two steps:

  1. Install the Vercel adapter to your projects dependencies using your preferred package manager. If youre using npm or arent sure, run this in the terminal:

      npm install @astrojs/vercel
    
  2. Add two new lines to your astro.config.mjs project configuration file.

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

Targets

You can deploy to different targets:

  • serverless: SSR inside a Node.js function.
  • static: generates a static website following Vercel's output formats, redirects, etc.

You can change where to target by changing the import:

import vercel from '@astrojs/vercel/serverless';
import vercel from '@astrojs/vercel/static';

Usage

📚 Read the full deployment guide here.

You can deploy by CLI (vercel deploy) or by connecting your new repo in the Vercel Dashboard. Alternatively, you can create a production build locally:

astro build
vercel deploy --prebuilt

Configuration

To configure this adapter, pass an object to the vercel() function call in astro.config.mjs:

analytics

Type: boolean
Available for: Serverless, Static
Added in: @astrojs/vercel@3.1.0

You can enable Vercel Analytics (including Web Vitals and Audiences) by setting analytics: true. This will inject Vercels tracking scripts into all your pages.

// astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';

export default defineConfig({
  output: 'server',
  adapter: vercel({
    analytics: true,
  }),
});

imagesConfig

Type: VercelImageConfig
Available for: Serverless, Static Added in: @astrojs/vercel@3.3.0

Configuration options for Vercel's Image Optimization API. See Vercel's image configuration documentation for a complete list of supported parameters.

// astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/static';

export default defineConfig({
  output: 'server',
  adapter: vercel({
    imagesConfig: {
      sizes: [320, 640, 1280],
    },
  }),
});

imageService

Type: boolean
Available for: Serverless, Static Added in: @astrojs/vercel@3.3.0

When enabled, an Image Service powered by the Vercel Image Optimization API will be automatically configured and used in production. In development, a built-in Squoosh-based service will be used instead.

// astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/static';

export default defineConfig({
  output: 'server',
  adapter: vercel({
    imageService: true,
  }),
});
---
import { Image } from 'astro:assets';
import astroLogo from '../assets/logo.png';
---

<!-- This component -->
<Image src={astroLogo} alt="My super logo!" />

<!-- will become the following HTML -->
<img
  src="/_vercel/image?url=_astro/logo.hash.png&w=...&q=..."
  alt="My super logo!"
  loading="lazy"
  decoding="async"
  width="..."
  height="..."
/>

includeFiles

Type: string[]
Available for: Serverless

Use this property to force files to be bundled with your function. This is helpful when you notice missing files.

// astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';

export default defineConfig({
  output: 'server',
  adapter: vercel({
    includeFiles: ['./my-data.json'],
  }),
});

excludeFiles

Type: string[]
Available for: Serverless

Use this property to exclude any files from the bundling process that would otherwise be included.

// astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';

export default defineConfig({
  output: 'server',
  adapter: vercel({
    excludeFiles: ['./src/some_big_file.jpg'],
  }),
});

Per-page functions

The Vercel adapter builds to a single function by default. Astro 2.7 added support for splitting your build into separate entry points per page. If you use this configuration the Vercel adapter will generate a separate function for each page. This can help reduce the size of each function so they are only bundling code used on that page.

// astro.config.mjs
import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel/serverless';

export default defineConfig({
  output: 'server',
  adapter: vercel(),
  build: {
    split: true,
  },
});

Vercel Edge Middleware

You can use Vercel Edge middleware to intercept a request and redirect before sending a response. Vercel middleware can run for Edge, SSR, and Static deployments. You may not need to install this package for your middleware. @vercel/edge is only required to use some middleware features such as geolocation. For more information see Vercels middleware documentation.

  1. Add a middleware.js file to the root of your project:

    // middleware.js
    export const config = {
      // Only run the middleware on the admin route
      matcher: '/admin',
    };
    
    export default function middleware(request) {
      const url = new URL(request.url);
      // You can retrieve IP location or cookies here.
      if (url.pathname === '/admin') {
        url.pathname = '/';
      }
      return Response.redirect(url);
    }
    
  2. While developing locally, you can run vercel dev to run middleware. In production, Vercel will handle this for you.

Warning

Trying to rewrite? Currently rewriting a request with middleware only works for static files.

Vercel Edge Middleware with Astro middleware

The @astrojs/vercel/serverless adapter can automatically create the Vercel Edge middleware from an Astro middleware in your code base.

This is an opt-in feature, and the build.excludeMiddleware option needs to be set to true:

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

Optionally, you can create a file recognized by the adapter named vercel-edge-middleware.(js|ts) in the srcDir folder to create Astro.locals.

Typings requires the @vercel/edge package.

// src/vercel-edge-middleware.js
/**
 *
 * @param options.request {Request}
 * @param options.context {import("@vercel/edge").RequestContext}
 * @returns {object}
 */
export default function ({ request, context }) {
  // do something with request and context
  return {
    title: "Spider-man's blog",
  };
}

If you use TypeScript, you can type the function as follows:

// src/vercel-edge-middleware.ts
import type { RequestContext } from '@vercel/edge';

export default function ({ request, context }: { request: Request; context: RequestContext }) {
  // do something with request and context
  return {
    title: "Spider-man's blog",
  };
}

The data returned by this function will be passed to Astro middleware.

The function:

  • must export a default function;
  • must return an object;
  • accepts an object with a request and context as properties;
  • request is typed as Request;
  • context is typed as RequestContext;

Limitations and constraints

When you opt in to this feature, there are few constraints to note:

  • The Vercel Edge middleware will always be the first function to receive the Request and the last function to receive Response. This an architectural constraint that follows the boundaries set by Vercel.
  • Only request and context may be used to produce an Astro.locals object. Operations like redirects, etc. should be delegated to Astro middleware.
  • Astro.locals must be serializable. Failing to do so will result in a runtime error. This means that you cannot store complex types like Map, function, Set, etc.

Troubleshooting

A few known complex packages (example: puppeteer) do not support bundling and therefore will not work properly with this adapter. By default, Vercel doesn't include npm installed files & packages from your project's ./node_modules folder. To address this, the @astrojs/vercel adapter automatically bundles your final build output using esbuild.

For help, check out the #support channel on Discord. Our friendly Support Squad members are here to help!

Contributing

This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!

Changelog

See CHANGELOG.md for a history of changes to this integration.