Restricting Netlify Functions to App only

Hi there,

Is there a way to restrict Netlify Functions only to the app run in netlify? For example, not have the function url accessible/callable by the public? I.e. {domain}/.netlify/functions/function-name will be blocked if accessed from the browser, but will be allowed if it’s an API call from the app?

The reason is, I am trying to create an API proxy and have a API service I am trying to pull data from that requires an API key, and I don’t want people to be accessing the data using the {domain}/.netlify/functions/function-name url.

Thanks,
Chris.

Hey @cvv

Yes you can do this. You will want to use the event.httpMethod to block GET requests. An example can be seen here: https://github.com/DavidWells/netlify-functions-workshop/blob/master/lessons-code-complete/use-cases/1-rest-api/functions/api.js#L7-L8

if (event.httpMethod !== 'POST') {
   return {
      statusCode: 500,
      body: 'ah ah ah didn't say the magic word'
   }
}

Additionally, if you’d like to authenticate the POST requests you can do so by checking the headers or using Netlify identity. https://github.com/DavidWells/netlify-functions-workshop/tree/master/lessons-code-complete/core-concepts/5-authenication

For more on serverless function authentication strategies see: https://github.com/DavidWells/serverless-auth-strategies

1 Like

Thanks David! The authentication method looks like what I’m looking for. I’ll give it a go!

Thanks!

1 Like