Access to restricted REST APIs with token

Hi there,

my website needs to access to a REST API. This REST API has restricted access and I need to pass an auth key to it. Where could I store the auth key in Netlify to give it the React app?

I cannot use a config file because Netlify gets the GitHub repository and the auth key has to be secret.

Best regards

There are 2 ways to handle this:

  1. Less secure way:

You add the secret to an environment variable in Netlify UI, React will use it while building the app and the key gets exposed in client-side JavaScript. It won’t be easily visible, but if someone is desperate enough, they can find it.

  1. More secure way:

You still add the secret as an environment variable to Netlify UI, but this time you use Netlify Functions to make calls to the REST API. This way, the secret is not exposed to client side, you call the REST API using the function and return the data to client side.

Let me know if you need more details about these.

Thank you @hrishikesh! Please let me know more about option 2 and how I can use Netlify Functions. I do my REST API requests like this: https://github.com/LupoBot/LupoWeb/blob/master/src/Util.js

Functions might sound nice, but you need to know that they do have their own set of limitations, for example:

  1. They’re limited to 10 sec time by default. You need to return a response within that time, or it will fail. For pro and above customers, we can change this limit to 26 seconds (max). So, if your destination rest API takes longer than that, this route is straight up closed.

  2. Functions don’t execute on CDN, they specifically run in US by default. Again, for pro and above, we can change the region to Asia or Eurpoe, but the reason why this information is important is that, the further away you’re from the execution point of the function, the longer it’ll take to send/receive data. So, depending on from where you’re accessing them, it might seem slower than the rest of the content.

  3. Functions run in Node.js environment, not browser environment. So, you might have to write the code differently, use different libraries, etc.

Apart from that, functions would basically work best with async JS like:

// import axios or node-fetch 
exports.handler = async event => {
  return fetch('your API', {
    headers: {
      Authorization: process.env.access_token //set a variable with name access_token in Netlify UI
    }
  }).then(response => {
    if (response.ok) {
      return response.json() // or response.text() or response.blob() depending on your needs
    } else {
      throw response.status
    }
  }).then(data => {
    // process your data here
      return {
        statusCode: 200,
        body: data // return the data for client-side processing
      }
  }).catch(error => {
    return {
      statusCode: 500,
      body: JSON.stringify(error)
    }
  })
}

So if you receive data from your API in JSON, the above code will simply send the JSON back to client without any additional processing.

So, in the client-side you’d have to call your function like: fetch('/.netlify/functions/foo/)and chain the.then()` callbacks and update the front-end accordingly.

Where should I add this code in my case https://github.com/LupoBot/LupoWeb/blob/master/src/Util.js? What does /.netlify/functions/foo/ do?

This will answer most of your questions:

Thank you, I tried it, but it does not work:

This is my code:

@hrishikesh I set both environment varialbes (BASE_URL and AUTH_KEY) which I use in the api.js

2 things to try:

Axios returns the data like res.data, so your

.then(data =>
  return {
    statusCode: 200,
    body: data
  }
)

Should actually be:

.then(response =>
  return {
    statusCode: 200,
    body: response.data
  }
)

If that doesn’t change anything, you should try to debug your functions by adding console.log() statements in it to see at what point the function is failing. So at each stage you could log stuff like:


import Axios from "axios";

exports.handler = async function(event) {
 console.log('url', process.env.BASE_URL + event.path)
 console.log('method', event.httpMethod)
/// and so on
    return Axios({
        url: process.env.BASE_URL + event.path,
        method: event.httpMethod,
        headers: {
            Authorization: process.env.AUTH_KEY
        }
    }).then(data => {
console.log(data) // or response.data
        return {
            statusCode: 200,
            body: data
        }
    }).catch(error => {
  console.log(error)
        return {
            statusCode: 500,
            body: JSON.stringify(error)
        }
    });
}

Then you can see in your functions’ console and see what can be going wrong. You could also paste the logs here so we could get some idea of what could be happening.

Additionally, it might as well be straight up timing out as it runs only for 10 seconds.

I fixed the response mistake and added debugs. These debugs do not appear in the console; there are the same errors as in my last screenshot. This is the deploy log:

2:36:12 PM: Build ready to start
2:36:14 PM: build-image version: c5b01a919d3e16af69445c5de0cacb49efbb1a23 (focal)
2:36:14 PM: build-image tag: v4.4.0
2:36:14 PM: buildbot version: 9deea8f876b3228119111d3a654f519dd1866bfe
2:36:14 PM: Fetching cached dependencies
2:36:14 PM: Starting to download cache of 167.0MB
2:36:15 PM: Finished downloading cache in 825.331483ms
2:36:15 PM: Starting to extract cache
2:36:23 PM: Finished extracting cache in 7.710313078s
2:36:23 PM: Finished fetching cache in 8.587566099s
2:36:23 PM: Starting to prepare the repo for build
2:36:23 PM: Preparing Git Reference refs/heads/master
2:36:23 PM: Parsing package.json dependencies
2:36:24 PM: Different functions path detected, going to use the one specified in the Netlify configuration file: 'functions' versus '' in the Netlify UI
2:36:24 PM: Starting build script
2:36:24 PM: Installing dependencies
2:36:24 PM: Python version set to 2.7
2:36:25 PM: Started restoring cached node version
2:36:27 PM: Finished restoring cached node version
2:36:28 PM: v16.13.0 is already installed.
2:36:28 PM: Now using node v16.13.0 (npm v8.1.0)
2:36:28 PM: Started restoring cached build plugins
2:36:28 PM: Finished restoring cached build plugins
2:36:29 PM: Attempting ruby version 2.7.2, read from environment
2:36:30 PM: Using ruby version 2.7.2
2:36:30 PM: Using PHP version 8.0
2:36:30 PM: Started restoring cached node modules
2:36:30 PM: Finished restoring cached node modules
2:36:31 PM: Started restoring cached go cache
2:36:31 PM: Finished restoring cached go cache
2:36:31 PM: go version go1.16.5 linux/amd64
2:36:31 PM: go version go1.16.5 linux/amd64
2:36:31 PM: Installing missing commands
2:36:31 PM: Verify run directory
2:36:32 PM: ​
2:36:32 PM: ────────────────────────────────────────────────────────────────
2:36:32 PM:   Netlify Build                                                 
2:36:32 PM: ────────────────────────────────────────────────────────────────
2:36:32 PM: ​
2:36:32 PM: ❯ Version
2:36:32 PM:   @netlify/build 18.20.1
2:36:32 PM: ​
2:36:32 PM: ❯ Flags
2:36:32 PM:   baseRelDir: true
2:36:32 PM:   buildId: 617d3c3ceb6f350007502eb1
2:36:32 PM:   deployId: 617d3c3ceb6f350007502eb3
2:36:32 PM: ​
2:36:32 PM: ❯ Current directory
2:36:32 PM:   /opt/build/repo
2:36:32 PM: ​
2:36:32 PM: ❯ Config file
2:36:32 PM:   /opt/build/repo/netlify.toml
2:36:32 PM: ​
2:36:32 PM: ❯ Context
2:36:32 PM:   production
2:36:32 PM: ​
2:36:32 PM: ────────────────────────────────────────────────────────────────
2:36:32 PM:   1. Build command from Netlify app                             
2:36:32 PM: ────────────────────────────────────────────────────────────────
2:36:32 PM: ​
2:36:32 PM: $ npm run build
2:36:33 PM: > lupoweb@0.1.0 build
2:36:33 PM: > react-app-rewired build
2:36:35 PM: Creating an optimized production build...
2:37:05 PM: Compiled successfully.
2:37:05 PM: 
2:37:05 PM: File sizes after gzip:
2:37:05 PM:   229.37 KB  build/static/js/2.bdb2ef86.chunk.js
2:37:05 PM:   42.98 KB   build/static/css/2.546a7300.chunk.css
2:37:05 PM:   20.97 KB   build/static/js/main.3c7f2a60.chunk.js
2:37:05 PM:   770 B      build/static/js/runtime-main.1f951500.js
2:37:05 PM:   432 B      build/static/css/main.a522a9d1.chunk.css
2:37:05 PM: The project was built assuming it is hosted at /.
2:37:05 PM: You can control this with the homepage field in your package.json.
2:37:05 PM: The build folder is ready to be deployed.
2:37:05 PM: You may serve it with a static server:
2:37:05 PM:   npm install -g serve
2:37:05 PM:   serve -s build
2:37:05 PM: Find out more about deployment here:
2:37:05 PM:   https://cra.link/deployment
2:37:05 PM: ​
2:37:05 PM: (build.command completed in 32.5s)
2:37:05 PM: ​
2:37:05 PM: ────────────────────────────────────────────────────────────────
2:37:05 PM:   2. Functions bundling                                         
2:37:05 PM: ────────────────────────────────────────────────────────────────
2:37:05 PM: ​
2:37:05 PM: Packaging Functions from functions directory:
2:37:05 PM:  - api.js
2:37:05 PM: ​
2:37:05 PM: ​
2:37:05 PM: (Functions bundling completed in 261ms)
2:37:05 PM: ​
2:37:05 PM: ────────────────────────────────────────────────────────────────
2:37:05 PM:   3. Deploy site                                                
2:37:05 PM: ────────────────────────────────────────────────────────────────
2:37:05 PM: ​
2:37:05 PM: Starting to deploy site from 'build'
2:37:05 PM: Creating deploy tree 
2:37:05 PM: Creating deploy upload records
2:37:05 PM: 0 new files to upload
2:37:05 PM: 1 new functions to upload
2:37:06 PM: Site deploy was successfully initiated
2:37:06 PM: ​
2:37:06 PM: (Deploy site completed in 975ms)
2:37:06 PM: ​
2:37:06 PM: ────────────────────────────────────────────────────────────────
2:37:06 PM:   Netlify Build Complete                                        
2:37:06 PM: ────────────────────────────────────────────────────────────────
2:37:06 PM: ​
2:37:06 PM: (Netlify Build completed in 33.8s)
2:37:06 PM: Starting post processing
2:37:06 PM: Post processing - HTML
2:37:06 PM: Post processing - header rules
2:37:06 PM: Post processing - redirect rules
2:37:06 PM: Post processing done
2:37:07 PM: Caching artifacts
2:37:07 PM: Started saving node modules
2:37:07 PM: Finished saving node modules
2:37:07 PM: Started saving build plugins
2:37:07 PM: Finished saving build plugins
2:37:07 PM: Started saving pip cache
2:37:07 PM: Site is live ✨
2:37:07 PM: Finished saving pip cache
2:37:07 PM: Started saving emacs cask dependencies
2:37:07 PM: Finished saving emacs cask dependencies
2:37:07 PM: Started saving maven dependencies
2:37:07 PM: Finished saving maven dependencies
2:37:07 PM: Started saving boot dependencies
2:37:07 PM: Finished saving boot dependencies
2:37:07 PM: Started saving rust rustup cache
2:37:07 PM: Finished saving rust rustup cache
2:37:07 PM: Started saving go dependencies
2:37:07 PM: Finished saving go dependencies
2:37:07 PM: Build script success
2:37:38 PM: Finished processing build request in 1m23.837254693s

This is the deploy log which is irrelevant. You need to check for Functions logs in Functions tab/

2:50:08 PM: 2021-10-30T12:50:08.814Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:08 PM: 1ee64b09 Duration: 150.35 ms	Memory Usage: 11 MB	2:50:08 PM: Unknown application error occurred
Runtime.UserCodeSyntaxError
2:50:08 PM: 2021-10-30T12:50:08.864Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:08 PM: 2021-10-30T12:50:08.877Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:08 PM: c893203d Duration: 163.63 ms	Memory Usage: 11 MB	2:50:08 PM: Unknown application error occurred
Runtime.UserCodeSyntaxError
2:50:08 PM: 1608d674 Duration: 170.89 ms	Memory Usage: 11 MB	2:50:08 PM: Unknown application error occurred
Runtime.UserCodeSyntaxError
2:50:08 PM: 2021-10-30T12:50:08.984Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:09 PM: 2021-10-30T12:50:09.013Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:09 PM: 2021-10-30T12:50:09.023Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:09 PM: 2021-10-30T12:50:09.084Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:09 PM: 2021-10-30T12:50:09.094Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:09 PM: 2021-10-30T12:50:09.228Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:09 PM: 2021-10-30T12:50:09.244Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:09 PM: 9a6d8ac6 Duration: 154.79 ms	Memory Usage: 11 MB	2:50:09 PM: Unknown application error occurred
Runtime.UserCodeSyntaxError
2:50:09 PM: 671525fe Duration: 178.34 ms	Memory Usage: 11 MB	2:50:09 PM: Unknown application error occurred
Runtime.UserCodeSyntaxError
2:50:09 PM: 2021-10-30T12:50:09.302Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:09 PM: 3a5061cb Duration: 157.44 ms	Memory Usage: 11 MB	2:50:09 PM: Unknown application error occurred
Runtime.UserCodeSyntaxError
2:50:09 PM: 2021-10-30T12:50:09.642Z	undefined	ERROR	Uncaught Exception 	{"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Cannot use import statement outside a module","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module","    at _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/index.js:43:30)","    at Module._compile (internal/modules/cjs/loader.js:999:30)","    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)","    at Module.load (internal/modules/cjs/loader.js:863:32)","    at Function.Module._load (internal/modules/cjs/loader.js:708:14)","    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)","    at internal/main/run_main_module.js:17:47"]}
2:50:09 PM: 51dc1c40 Duration: 154.98 ms	Memory Usage: 11 MB	2:50:09 PM: Unknown application error occurred
Runtime.UserCodeSyntaxError

Oh right, I totally forgot about this!

You’re using import statement, but by default Functions don’t support it. So you could change it to const Axios = require('axios').

Thank you! This is the current function error:

3:14:24 PM: 899de7c0 Duration: 3.26 ms	Memory Usage: 59 MB	3:14:24 PM: 5ad0f391 INFO   url 45.82.121.211:7000/v1/bot
3:14:24 PM: 5ad0f391 INFO   method GET
3:14:24 PM: 5ad0f391 INFO   Error: connect EINVAL 0.0.27.88:80 - Local (0.0.0.0:0)
    at internalConnect (net.js:923:16)
    at defaultTriggerAsyncIdScope (internal/async_hooks.js:364:12)
    at GetAddrInfoReqWrap.emitLookup [as callback] (net.js:1066:9)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:68:8) {
  errno: 'EINVAL',
  code: 'EINVAL',
  syscall: 'connect',
  address: '0.0.27.88',
  port: 80,
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      Authorization: 'REPLACED',
      'User-Agent': 'axios/0.23.0'
    },
    url: '45.82.121.211:7000/v1/bot',
    method: 'get',
    data: undefined
  },
  request: Writable {
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: true,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: true,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      bufferedRequest: null,
      lastBufferedRequest: null,
      pendingcb: 0,
      prefinished: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: false,
      bufferedRequestCount: 0,
      corkedRequestsFree: [Object]
    },
    writable: true,
    _events: [Object: null prototype] {
      response: [Function: handleResponse],
      error: [Function: handleRequestError]
    },
    _eventsCount: 2,
    _maxListeners: undefined,
    _options: {
      maxRedirects: 21,
      maxBodyLength: 10485760,
      protocol: 'http:',
      path: '/v1/bot',
      method: 'GET',
      headers: [Object],
      agent: undefined,
      agents: [Object],
      auth: undefined,
      hostname: '7000',
      port: null,
      nativeProtocols: [Object],
      pathname: '/v1/bot'
    },
    _ended: true,
    _ending: true,
    _redirectCount: 0,
    _redirects: [],
    _requestBodyLength: 0,
    _requestBodyBuffers: [],
    _onNativeResponse: [Function],
    _currentRequest: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [Socket],
      connection: [Socket],
      _header: 'GET /v1/bot HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Authorization: REPLACED +
        'User-Agent: axios/0.23.0\r\n' +
        'Host: 7000\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      insecureHTTPParser: undefined,
      path: '/v1/bot',
      _ended: false,
      res: null,
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: '7000',
      protocol: 'http:',
      _redirectable: [Circular],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    _currentUrl: 'http://7000/v1/bot',
    [Symbol(kCapture)]: false
  },
  response: undefined,
  isAxiosError: true,
  toJSON: [Function: toJSON]
}

Based on this:

You need to try pre-pending the URL with http://

Oh thank you, I thought I had the http. Now, the console logs of the function are correct and printed the data received from the api. But on the website, there are still these errors in the console and the data does not render on the website:

Could you try to change: body: res.data to body: JSON.stringify(res.data)?

Nice, thank you, it is working! But there’s still a problem: Every user can access to this api via https://lupobot.netlify.app/.netlify/functions/api/bot but this function should only be usable for the website itself.

Yeah, there’s no ‘real’ way to block that. Even if you block it, anyone desperate can still use curl, Postman, etc. and be able to see the data.

The only solution is to create temporary users in Netlify Identity and authenticate in functions using that - but it’s recommended only for Identity unlimited plan that would cost $99.

You can add primitive security measures, but as I said, they can be bypassed easily. If you’re still interested, let me know.

But that was my initial question? What is the advantage of using Netlify Functions when I could use the REST API directly? That is the same result if both have no restricted access …