Adding just a bit of backend functionality to your Netlify-hosted static site is a perfect use-case for serverless functions. Let's get up and running!
Why?
Whether you want to keep a third-party or proprietary API key or secret from being shipped to the browser, or you just need a little server-side functionality, a serverless function can bridge the gap.
Prepare Your Project
First, we need to make sure our project is hosted on Netlify.
Let's connect our project to a Netlify and get set up using Netlify Dev, which will allow us to test our functions locally:
- Create a Netlify account if you don't have one already.
- Ensure you have the Netlify CLI installed locally. You can do this by running
npm i -g netlify-cli
. If you run into a permissions issue, check out the NPM docs on the issue. - Authenticate with Netlify by running
netlify login
. - Initialize your Netlify project by running
netlify init
. This will create a site on Netlify and associate your project with that new site.
Configure a Functions Directory
Now that we're set up with a Netlify project, we need to tell Netlify where to find our functions.
- Create a new directory at the root of your project. I typically name this directory something like,
/api
. - Create a config file to tell Netlify where to look for your functions:
# netlify.toml
[dev]
functions: '/api'
Create a Function
Now that Netlify knows where to look for our functions, we can write our first one!
Create a new file in the /api
directory:
// testy.js
exports.handler = async (event, context) => {
return {
statusCode: 200,
body: JSON.stringify({
message: 'yup, it works'
})
}
}
Test Locally Using Netlify Dev
With our function created, let's make sure it works!
- Start your dev server by running
netlify dev
. You may need to choose or configure a start command. - Visit http://localhost:8888/.netlify/functions/testy
Deploy
If your local function is working correctly, go ahead and deploy it to Netlify with netlify deploy
!
Thanks for reading! Need some help? Feel free to reach out.
Top comments (0)