Skip to content

allowing requests from any origin #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from

Conversation

huntercaron
Copy link

Had some issues with local development requests not working due to cross-origin calls. Adding a request header to allow them relieved any issues.

@biilmann
Copy link
Member

This would risk making local and remote setups work differently, since the remote setup wont send cors headers unless manually returned from your lambda

@lukebussey
Copy link

You should be proxying /.netlify/functions/ so the paths are the same as the deployed code instead.

@mdxprograms
Copy link

I've added the proxy and I still have issues with cors. Locally port 9000 is serving lambdas and app is on 3000. I matched the react example repo as far as proxy setup in package.json.

@roachnt
Copy link

roachnt commented Jul 31, 2018

Any reason why this hasn't been merged? This has become an annoying issue.

@Offirmo
Copy link

Offirmo commented Aug 24, 2018

100% for this to be merged. Dev setups are complicated and this helps.

@omarchehab98
Copy link

I don't see a reason to merge this, it will make the development and production environments work differently. Here's how to serve your client code and proxy your functions using express.

const url = require('url');
const express = require('express');
const proxy = require('express-http-proxy');
const app = express();

app.use('/.netlify/functions/*', proxy('http://127.0.0.1:9000', {
  proxyReqPathResolver: (req) => {
    const thePath = url.parse(req.baseUrl).path;
    const query = url.parse(req.url).query;
    // '/.netlify/functions'.length == 19
    return thePath.substr(19) + (query ? `?${query}` : '');
  },
}));

// Serve static files here

app.listen(process.env.PORT || 3000);

@Offirmo
Copy link

Offirmo commented Sep 18, 2018

@biilmann @huntercaron in response to your concerns: when coupling a static app and lambda (a common approach), it's a big pain to have to setup a proxy on top of both the static app and netlify-lambda.

On the ground it would make prod and dev different, well it's most likely the case in 99% of the situations. Netlify-lambda serve is only vaguely attempting to emulate amazon lambdas, there are many differences (error handling for ex.)

In a dev env, I expect everything to work as simply as possible. Having for ex. to launch parcel + netlify-lambda serve + a proxy is a pain.

@Offirmo
Copy link

Offirmo commented Oct 12, 2018

Or at least make this an option! Or serving files could be a feature of this tool! (but wouldn't help a webpack watch or a parcel serve)

@swyxio
Copy link
Contributor

swyxio commented Oct 12, 2018

@Offirmo open to considering. what did you think of @omarchehab98's solution above - what if we just put that in the docs for people?

@8eecf0d2
Copy link
Contributor

8eecf0d2 commented Oct 14, 2018

I think this issue could be better resolved by exposing the lambda handling methods from netlify-lambda and wrapping them in another package, say netlify-local, which serves lambdas at /.netlify/lambda and tries to emulate the publish folder as per netlify.toml all on the same server / port. Such a package would better emulate the netlify service and remove cors issues caused by the different server used for running lambdas locally.

See ref below for example implementation of a netlify-local package.

@Offirmo
Copy link

Offirmo commented Oct 14, 2018

@sw-yx I need to re-spike on netlify-lambda to form an opinion. Will comment again.

8eecf0d2 added a commit to 8eecf0d2/netlify-local that referenced this pull request Oct 15, 2018
@lastmjs
Copy link

lastmjs commented Oct 16, 2018

I would really like this, I've spent a few hours just trying to get this thing working, dealing with CORS.

@abumalick
Copy link

I got stuck some time too on this. I use nuxt on this project and often use gatsby or create react app. I think it is difficult to serve functions on the same port in development with these framework.

I am ok to try a solution like what @omarchehab98 wrote, but I doubt that it will work correctly with webpack's hot module replacement. (I tried and failed)

It would be so simple for us to be able to launch netlify-lambda --no-cors serve functions. 🚀I would be very happy with this.

In the meanwhile, I found these workarounds to be able to test my functions in development:

The first I used is: use this extension to disable CORS on chrome: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en .

At some point I had problems to make the extension work. Instead I tried to handle cors in the function directly:

exports.handler = function(event, context, callback) {
  if (process.env.ENABLE_CORS && event.httpMethod === 'OPTIONS') {
    const response = {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers':
          'Origin, X-Requested-With, Content-Type, Accept',
      },
      body: JSON.stringify({message: 'You can use CORS'}),
    }
    callback(null, response)
    return
  }
  if (event.httpMethod === 'POST') {
    const headers = process.env.ENABLE_CORS
      ? {
              'Access-Control-Allow-Origin': '*',
              'Access-Control-Allow-Headers':
                'Origin, X-Requested-With, Content-Type, Accept',
       }
       : {}

       callback(null, {
          headers,
          statusCode: 200,
          body: JSON.stringify({
            result: 'SUCCESS'
          }),
        })
        return
      })

Setting an ENV variable ENABLE_CORS only in development would disable CORS in dev and let it in production.

I don't think this code is perfect (I am pretty new to serverless), but it works for me.

Thanks for netlify-lambda !

@swyxio
Copy link
Contributor

swyxio commented Nov 6, 2018

i will be putting together a gatsby example for folks that uses netlify lambda. i think the proxying is easier than people think...

@abumalick
Copy link

abumalick commented Nov 18, 2018

Thank you @sw-yx

After reading what you said, I tried to configure proxy with nuxt.js framework and it works very well without CORS issue now.

Here is the configuration based on the webpack config in the Readme:

// in nuxt.config.js
// ...
modules: ['@nuxtjs/proxy'],
proxy: {
  '/.netlify': {
    target: 'http://localhost:9000',
    pathRewrite: {'^/.netlify/functions': ''},
  },
},
// ...

As you said, it is easier than I thought.

@swyxio
Copy link
Contributor

swyxio commented Dec 3, 2018

and i forgot my gatsby starter - i put in in the docs but not here - https://github.com/sw-yx/jamstack-hackathon-starter

thanks @abumalick i will put your instructions on the docs

@swyxio swyxio closed this Dec 3, 2018
@abumalick
Copy link

abumalick commented Feb 23, 2019

I understand that setting up a proxy is the good way to do it. But sometimes it can be a lot of trouble, it is why I think it would be nice to allow CORS from the command line by adding a flag.

I am using netlify functions with jekyll, and I am forced to use my workaround because I have no idea how to configure a proxy with it.

@abumalick
Copy link

I mean this workaround: allow CORS based on an env variable

#28 (comment)

@corysimmons
Copy link

Please do something like $ netlify-lambdas --no-cors as mentioned above. It's opt-in, and would make localhost easier.

CORS isn't a problem on live servers (like Netlify) so just let people dev easily locally and push to live server and everything JustWork™️.

I hate having to set up an Express server just to enable cors (then forward all requests to index.html so react-router/etc. works...) just to avoid these annoying errors for local dev... Does a custom Express server even work on Netlify since "Netlify <3 static" so much? 😩

Dogma over pragmatism takes years away from my life just working around stuff exactly like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.