- Install
netlify-lambda
in your Gatsby project
npm install netlify-lambda --save
- Create a
functions/src
subdirectory for the Lambda functions' source code
<root>
└── functions/
└── src/
-
Add
functions/dist
to.gitignore
. Thefunctions/dist
folder is autogenerated by netlify-lambda during the build process -
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"
}
- 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"
- Configure Gatsby to proxy
/.netlify/functions
requests to the netlify-lambda server. Ingatsby-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/": "",
},
})
)
},
}
- Add a
hello.js
file tofunctions/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',
})
}
- Start the netlify-lambda server
npm run start-server
-
Open a browser and go to http://localhost:9000/hello. It should render "Hello, World"
-
Start Gatsby in another terminal window
npm run develop
- Go to http://localhost:8000/.netlify/functions. It should render the same "Hello, World" from step 3.