Skip to content
Last updated on March 2, 2023
20 min read

Gatsby on Vercel

Learn how to use Vercel's features with Gatsby.

Gatsby is an open-source static-site generator. It enables developers to build fast and secure websites that integrate different content, APIs, and services.

Gatsby also has a large ecosystem of plugins and tools that improve the development experience. Vercel supports many Gatsby features, including Server-Side Rendering, Deferred Static Generation, API Routes, and more.

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

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

Gatsby v4+ sites deployed to Vercel will automatically detect Gatsby usage and install the @vercel/gatsby-plugin-vercel-builder plugin.

To deploy your Gatsby site to Vercel, do not install the @vercel/gatsby-plugin-vercel-builder plugin yourself, or add it to your gatsby-config.js file.

Gatsby v5 sites require Node.js 18, which is currently the default version used for new Vercel builds.

Vercel persists your Gatsby project's .cache directory across builds.

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.

You can server-render pages in your Gatsby application on Vercel using Gatsby's native Server-Side Rendering API. These pages will be deployed to Vercel as Serverless Functions.

To server-render a Gatsby page, you must export an async function called getServerData. The function can return an object with several optional keys, as listed in the Gatsby docs. The props key will be available in your page's props in the serverData property.

The following example demonstrates a server-rendered Gatsby page using getServerData:


import type { GetServerDataProps, GetServerDataReturn } from 'gatsby';
type ServerDataProps = {
  hello: string;
const Page = (props: PageProps) => {
  const { name } = props.serverData;
  return <div>Hello, {name}</div>;
export async function getServerData(
  props: GetServerDataProps,
): GetServerDataReturn<ServerDataProps> {
  try {
    const res = await fetch(``);
    return {
      props: await res.json(),
  } catch (error) {
    return {
      status: 500,
      headers: {},
      props: {},
export default Page;

To summarize, SSR with Gatsby 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

Deferred Static Generation (DSG) allows you to defer the generation of static pages until they are requested for the first time.

To use DSG, you must set the defer option to true in the createPages() function in your gatsby-node file.


import type { GatsbyNode } from 'gatsby';
export const createPages: GatsbyNode['createPages'] = async ({ actions }) => {
  const { createPage } = actions;
    defer: true,
    path: '/using-dsg',
    component: require.resolve('./src/templates/using-dsg.js'),
    context: {},

See the Gatsby docs on DSG to learn more.

To summarize, DSG with Gatsby on Vercel:

Allows you to defer non-critical page generation to user request, speeding up build times
Works out of the box when you deploy on Vercel
Can yield dramatic speed increases for large sites with content that is infrequently visited

You can add API Routes to your Gatsby site using the framework's native support for the src/api directory. Doing so will deploy your routes as Serverless Functions. These Serverless Functions can be used to fetch data from external sources, or to add custom endpoints to your application.

The following example demonstrates a basic API Route using Serverless Functions:


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

To view your route locally, run the following command in your terminal:


gatsby develop

Then navigate to http://localhost:8000/api/handler in your web browser.

To summarize, API Routes with Gatsby on Vercel:

Scale to zero when not in use
Scale automatically with traffic increases
Can be tested as Serverless Functions in your local environment

Gatsby does not have native support for Edge Functions.

To use Edge Functions in your Gatsby project on Vercel, you must create an api directory at the root of your project. Note that this is different from the src/api/ directory, which is where Vercel detects and deploys Serverless Functions.

The following example demonstrates a basic Edge Function:


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

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

To summarize, Edge Functions with Gatsby on Vercel:

Enable you to respond to user requests with dynamic content at low latency, at scale
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

Gatsby does not have native framework support for using Edge Middleware.

However, you can still use Edge Middleware with your Gatsby site by creating a middeware.js or middeware.ts file in your project's root directory.

The following example demonstrates middleware that adds security headers to responses sent to users who visit the /example route in your Gatsby application:


import { next } from '@vercel/edge';
export const config = {
  // Only run the middleware on the example route
  matcher: '/example',
export default function middleware(req: Request): Response {
  return next({
    headers: {
      'Referrer-Policy': 'origin-when-cross-origin',
      'X-Frame-Options': 'DENY',
      'X-Content-Type-Options': 'nosniff',
      'X-DNS-Prefetch-Control': 'on',
        'max-age=31536000; includeSubDomains; preload',

To summarize, Edge Middleware with Gatsby 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 via a matcher config.

Uses our lightweight Edge Runtime to keep costs low and responses fast

Core Web Vitals are supported for Gatsby v4+ projects with no initial configuration necessary.

When you deploy a Gatsby v4+ site on Vercel, we automatically install the @vercel/gatsby-plugin-vercel-analytics package and add it to the plugins array in your gatsby-config.js file.

We do not recommend installing the Gatsby analytics plugin yourself.

To access your Core Web Vitals data, you must enable Vercel analytics in your project's dashboard. See our quickstart guide to do so now.

To summarize, using Web Vitals with Gatsby on Vercel:

Enables you to track traffic performance metrics, such as First Contentful Paint, or First Input Delay

Enables you to view performance analytics by page name and URL for more granular analysis

Shows you a score for your app's performance on each recorded metric, which you can use to track improvements or regressions

While Gatsby does provide an Image plugin, it is not currently compatible with Vercel Image Optimization.

If this is something your team is interested in, please contact our sales team.

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

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