Is it possible to fetch a netlify function from another domain

Is it possible to send a fetch request to a netlify lambda function from a outside domian, I thought I had this working before. So I want to send a fetch request from dev.websit.com to https://website-dev.netlify.app/.netlify/functions/checkout

The error I am getrting is a cors


Access to fetch at 'https://website-dev.netlify.app/.netlify/functions/checkout' from origin 'http://dev.website.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

the function looks like this

require("dotenv").config()

const stripe = require("stripe")(process.env.REACT_APP_STRIPE_API_SECRET)
const validateCartItems = require("use-shopping-cart/src/serverUtil")
  .validateCartItems

exports.handler = async (event, context) => {
  try {
    const productJSON = JSON.parse(event.body)

    console.log(productJSON.line_items)

    var test = Object.entries(productJSON)[0][1]

    console.log(test)

    var values = productJSON.values

    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      billing_address_collection: "auto",
      shipping_address_collection: {
        allowed_countries: ["CA"],
      },
      success_url: `${process.env.URL}/success`,
      cancel_url: `${process.env.URL}/cancelled`,
      line_items: test,
      mode: "payment",
      metadata: values,
    })

    console.log(session.id)

    return {
      statusCode: 200,
      body: JSON.stringify({ sessionId: session.id }),
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Methods": "GET, POST",
      },
    }
  } catch (err) {
    return { statusCode: 500, body: err.toString() }
  }
}

and I have a netlify.toml file with the following settings
[build]
functions =“functions/”

[[headers]]

Define which paths this specific [[headers]] block will cover.

for = “/"
[headers.values]
Access-Control-Allow-Origin = "

Thanks ahead of time

Is it possible to send a fetch request cross domain to a netlify lambda function I get the following error

Access to fetch at ‘https://website-dev.netlify.app/.netlify/functions/stripe-checkout-session-fix’ from origin ‘http://dev.website.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

This is my webhook

require("dotenv").config()

const stripe = require("stripe")(process.env.REACT_APP_STRIPE_API_SECRET)
const validateCartItems = require("use-shopping-cart/src/serverUtil")
  .validateCartItems

exports.handler = async (event, context) => {
  try {
    const productJSON = JSON.parse(event.body)

    console.log(productJSON.line_items)

    var test = Object.entries(productJSON)[0][1]

    console.log(test)

    var values = productJSON.values

    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      billing_address_collection: "auto",
      shipping_address_collection: {
        allowed_countries: ["CA"],
      },
      success_url: `${process.env.URL}/success`,
      cancel_url: `${process.env.URL}/cancelled`,
      line_items: test,
      mode: "payment",
      metadata: values,
    })

    console.log(session.id)

    return {
      statusCode: 200,
      body: JSON.stringify({ sessionId: session.id }),
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Methods": "GET, POST",
      },
    }
  } catch (err) {
    return { statusCode: 500, body: err.toString() }
  }
}

and I have a netlify.toml file

[build]
  functions ="functions/"

[[headers]]
  # Define which paths this specific [[headers]] block will cover.
  for = "/*"
    [headers.values]
    Access-Control-Allow-Origin = "*"

Thanks in advance

Hi @wispyco,

You’ll also want to allow the OPTION method as well, since that is the first request by the browser to determine if the request is allowed before doing a GET or POST. Let me know how that goes.

I added like so
“Access-Control-Allow-Methods”: “GET, POST, OPTION”,

but am still gettign the error But in the error it is complaining about the Access-Control-Allow-Origin, and I have that in the lambda and the netlify.toml

So I am stuck here

Your function, not your html, would need that header. The custom headers functionality WILL NOT apply to functions; only what your function returns can add headers there.

Seems like you’ve removed that function in the meantime - did you abandon or did you end up implementing differently?

Oh I don’t know what you mean by not your html. I am not setting any headers in html.

I have this in my netlify function

return {
      statusCode: 200,
      body: JSON.stringify({ sessionId: session.id }),
      // // more keys you can return:
      // headers: { "headerName": "headerValue", ... },
      // isBase64Encoded: true,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Methods": "GET, POST, OPTION",
      },
    }

The actuall location of the function is different than what I posted, I just posted what would be an example url. The function is up.

That looks right to me! At this point, I’d start playing with things that seem like they shouldn’t matter but might: move headers above body in the response, try single quotes instead of double, etc.