Skip to content

imorente/gatsby-netlify-functions

Repository files navigation

How to integrate Gatsby with Netlify Functions

Set up netlify-lambda

  1. Install netlify-lambda in your Gatsby project
npm install netlify-lambda --save
  1. Create a functions/src subdirectory for the Lambda functions' source code
<root>
└── functions/
    └── src/
  1. Add functions/dist to .gitignore. The functions/dist folder is autogenerated by netlify-lambda during the build process

  2. Add scripts to the package.json to build the Lambda functions and start the netlify-lambda server

scripts: {
  "build-server": "netlify-lambda build functions/src",
  "start-server": "netlify-lambda serve functions/src"  
}
  1. Add a netlify.toml to the root of the repository to tell Netlify how to build the site and functions
  [build]
    # `npm run build` builds the client side (Gatsby site)
    # `npm run build-server` builds the server side (Lambda functions)
    # Both build commands can be chained together with `&&`
    command = "npm run build && npm run build-server"

    # Directory with files generated by the client-side build
    publish = "public"

    # Directory with files generated by the server-side build
    functions = "functions/dist"
  1. Configure Gatsby to proxy /.netlify/functions requests to the netlify-lambda server. In gatsby-config.js add
var proxy = require("http-proxy-middleware")

module.exports = {
  developMiddleware: app => {
    app.use(
      "/.netlify/functions/",
      proxy({
        target: "http://localhost:9000",
        pathRewrite: {
          "/.netlify/functions/": "",
        },
      })
    )
  },
}

Verify setup

  1. Add a hello.js file to functions/src with a basic "Hello World" Lambda function
<root>
└── functions/
    └── src/
        └── hello.js
// hello.js
exports.handler = function(event, context, callback) {
  callback(null, {
    statusCode: 200,
    body: 'Hello, World',
  })
}
  1. Start the netlify-lambda server
npm run start-server
  1. Open a browser and go to http://localhost:9000/hello. It should render "Hello, World"

  2. Start Gatsby in another terminal window

npm run develop
  1. Go to http://localhost:8000/.netlify/functions. It should render the same "Hello, World" from step 3.

About

Gatsby default starter integrated with netlify-lambda

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published