Getting CORS error while calling a lambda function

I’m trying to call a lambda function I’ve created under /api/src/functions/hello.js. The content is this:

export const handler = (event, context, callback) => {
  return callback(null, { status: 200, body: { Hello: 'World' } })
}

And my component:

import { useState, useEffect } from 'react'
import BaseLayout from 'src/layouts/BaseLayout'

const HomePage = () => {
  const [msg, setMsg] = useState('Dude')

  useEffect(() => {
    fetch('http://localhost:8911/hello').then((r) => setMsg(r.json().Hello))
  })

  return <BaseLayout>Hello {msg}</BaseLayout>
}

export default HomePage

But I’m getting a CORS error in the console.

I am able to hit the endpoint directly from the browser.

What’s the recommended way for calling a custom function ?

Thanks!

We proxy requests from the “web” side to the “api” side, try accessing your lambda function via: https://localhost:8910/.netlify/functions/hello/

2 Likes

Great, it works! Thanks you!

Is this URL abstracted away somewhere so that I can use it both locally and when deployed to Netlify ?

Thanks gain,
DV

Yup! It’s configurable via redwood.toml:

It’s the default way that it’s handled in Netlify.

➜ cat ../redwood.toml
[web]
  port = 8910
  apiProxyPath = "/.netlify/functions"

[api]
  port = 8911
1 Like

Is there a way to have that config accessible to the web side ?

This doesn’t work:

import { getConfig } from '@redwoodjs/internal'

const redwoodConfig = getConfig()
const url = `http://localhost:${redwoodConfig.api.port}${redwoodConfig.web.apiProxyPath}/hello`

Get a Cannot find module 'fs' error.

Thanks.

Ah, sorry… I misunderstood your question.

You can grab it from over here:

import { __REDWOOD__ as config } from '@redwoodjs/web'

const url = `${config.API_PROXY_PATH}/hello`
// /.netlify/functions/hello

We will probably rename __REDWOOD__ to something friendlier, we did not intend for it to be used externally, but it makes sense that it would be.

1 Like

It works!

Thank you so much!

  • Daniel
2 Likes

@peterp given your answer, how do you envision having multiple types of “clients” consuming those functions?

If I develop a mobile app and want to consume data from my GraphQL API created with Redwood, do I have to proxy everything through the web server?

We’re going to support multiple clients, and I think if the client is web-based then we’ll supply a way to proxy those requests via webpack, with instructions on how to match in production.

If the client is a mobile app (react-native) then CORS doesn’t apply and you can target your API server directly.

Ah, of course. Every now and then I forget that CORS is only enforced by browsers :roll_eyes:

Thanks!