Home
Support Forums

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.

1 Like

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

2 Likes

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

Thanks!

2 Likes

+1 thank you David, really great resources you linked to!

1 Like

Sorry for the bump.

What if our app already handles user management so we’re not using Netlify Identity? How do we restrict netlify functions to only logged-in users of our app?

In my case, I don’t have access to my app’s server side code (because it’s built on a 3rd party platform). But I do have the ability to retrieve the user token generated by my app, then pass it to Netlify or wherever if needed.

Could someone tell me if this the workflow please:

  1. My app passes the user token to the Netlify Function
  2. Netlify Function validates the user token against my app? How?

I’m stuck on the implementation details.

hi there vcamp, we haven’t forgotten about you! hope to get some more eyes on this soon.

@perry

Ok thanks! No rush… I decided to use a workaround… I wrote a little script that checks if the user’s auth token is valid and required it in all my netlify functions.

However still curious about the ~official~ Netlify way to solve this problem.