1 min read

Gatsby on Vercel

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

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.

To get started with Gatsby on Vercel:

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

pages/example.tsx
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(`https://example-data-source.com/api/some-data`);
    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

Learn more about SSR

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.

pages/index.tsx
import type { GatsbyNode } from 'gatsby';
 
export const createPages: GatsbyNode['createPages'] = async ({ actions }) => {
  const { createPage } = actions;
  createPage({
    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

Learn more about DSG

Gatsby supports Deferred Static Generation.

The static rendered fallback pages are not generated at build time. This differentiates it from incremental static regeneration (ISR). Instead, a Vercel Function gets invoked upon page request. And the resulting response gets cached for 10 minutes. This is hard-coded and currently not configurable.

See the documentation for Deferred Static Generation.

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:

src/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,
  });
}

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

terminal
gatsby develop

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

Vercel does not currently have first-class support for dynamic API routes in Gatsby. For now, using them requires the workaround described in this section.

To use Gatsby's Dynamic API routes on Vercel, you must:

  1. Define your dynamic routes in a vercel.json file at the root directory of your project, as shown below:

    vercel.json
    {
      "rewrites": [
        {
          "source": "/api/blog/:id",
          "destination": "/api/blog/[id]"
        }
      ]
    }
  2. Read your dynamic parameters from req.query, as shown below:

    api/blog/[id].ts
    import type { VercelRequest, VercelResponse } from '@vercel/node';
     
    export default function handler(
      request: VercelRequest & { params: { id: string } },
      response: VercelResponse,
    ) {
      console.log(`/api/blog/${request.query.id}`);
      response.status(200).json({
        body: request.body,
        query: request.query,
        cookies: request.cookies,
      });
    }

Although typically you'd access the dynamic parameter with request.param when using Gatsby, you must use request.query on Vercel.

Splat API routes are dynamic wildcard routes that will match anything after the splat ([...]). Vercel does not currently have first-class support for splat API routes in Gatsby. For now, using them requires the workaround described in this section.

To use Gatsby's splat API routes on Vercel, you must:

  1. Define your splat routes in a vercel.json file at the root directory of your project, as shown below:

    vercel.json
    {
      "rewrites": [
        {
          "source": "/api/products/:path*",
          "destination": "/api/products/[...]"
        }
      ]
    }
  2. Read your dynamic parameters from req.query.path, as shown below:

    api/products/[...].ts
    import type { VercelRequest, VercelResponse } from '@vercel/node';
     
    export default function handler(
      request: VercelRequest & { params: { path: string } },
      response: VercelResponse,
    ) {
      console.log(`/api/products/${request.query.path}`);
      response.status(200).json({
        body: request.body,
        query: request.query,
        cookies: request.cookies,
      });
    }

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

Learn more about Gatsby API Routes

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:

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

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

Learn more about Edge Functions

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:

middleware.ts
import { next } from '@vercel/edge';
 
export const config = {
  // Only run the middleware on the example route
  matcher: '/example',
};
 
export default function middleware(request: 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',
      'Strict-Transport-Security':
        '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 through a matcher config
  • Uses our lightweight Edge Runtime to keep costs low and responses fast

Learn more about Edge Middleware

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 Speed Insights with Gatsby on Vercel:

Learn more about Speed Insights

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.

Learn more about Image Optimization

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:

Last updated on June 13, 2024