Gatsby

This guide shows you how to deploy an Gatsby application on Layer0.

Example

Connector

This framework has a connector developed for Layer0. See Connectors for more information.

System Requirements

Getting Started

If you don’t already have a Gatsby application, you can create one using:

Terminal
npm install -g gatsby-cli
gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-hello-world

You should now have a working Gatsby site. Run gatsby develop to see the application running on localhost:8000.

To deploy your Gatsby on Layer0:

  1. Install the Layer0 CLI globally:
Terminal
npm install -g @layer0/cli
  1. Run the following in the root folder of your project. This will configure your project for Layer0.
Terminal
0 init

This will automatically add all of the required dependencies and files to your project. These include:

  • The @layer0/core package
  • The @layer0/gatsby package
  • The @layer0/cli package
  • layer0.config.js
  • routes.js - A default routes file that sends all requests to your Gatsby static site. Update this file to add caching or proxy some URLs to a different origin.

Running Locally

You can test the integration of the Layer0 router with your gatsby site locally using:

Terminal
0 dev

Deploying

Deploying requires an account on Layer0. Sign up here for free. Once you have an account, you can deploy to Layer0 by running the following in the root folder of your project:

Terminal
0 deploy

See Deploying guide for more information.

Routing

The default routes.js file created by 0 init sends all requests to the Gatsby static site.

JavaScript
// This file was automatically added by 0 deploy.
// You should commit this file to source control.

const { Router } = require('@layer0/core/router')
const { gatsbyRoutes } = require('@layer0/gatsby')

module.exports = new Router().use(gatsbyRoutes)

Adding routes to a different origin

To proxy some URLs to a different origin, you need first to configure that origin in your layer0.config.js file.

For example:

JavaScript
// layer0.config.js

module.exports = {
  backends: {
    legacy: {
      domainOrIp: process.env.LEGACY_BACKEND_DOMAIN || 'legacy.my-site.com',
      hostHeader: process.env.LEGACY_BACKEND_HOST_HEADER || 'legacy.my-site.com',
    },
  },
}

Using environment variables here allows you to configure different legacy domains for each Layer0 environment.

Then you can add routing and caching rules to your routes.js file. Note that gatsbyRoute must be declared last as it acts as a fallback route.

For example:

JavaScript
// routes.js

const { Router } = require('@layer0/core/router')
const { gatsbyRoutes } = require('@layer0/gatsby')

module.exports = new Router()
  .get('/some/legacy/url/:p', ({ proxy }) => {
    proxy('legacy')
  })
  .use(gatsbyRoutes)

Check Routing and Caching guides for more information.