CORS configuration ineffective.

default discord avatar
clhomelast year
3 6

When I configured cors: '*' in payload.config.ts, I still got a CORS error when accessing it with other ports. Can anyone please advise on how to solve this issue?

  cors: '*', 
  rateLimit: {
    trustProxy: true,
    window: 2 * 60 * 1000, // 2 minutes
    max: 2400, // limit each IP per windowMs
  },

image-20230404223530906

  • Selected Answer
    default discord avatar
    clhomelast year

    I have found a solution to fix the CORS issue, but it's not elegant. I believe the server.ts configuration not working should be considered a bug.The code is written in server.ts.

    var cors = require('cors');
    var corsOptions = {
      origin: '*',
      credentials: true,
      optionsSuccessStatus: 200
    }
    
    app.use(cors(corsOptions));

    it need run“yarn add cors” first,

    3 replies
  • discord user avatar
    JarrodMFlesch
    last year

    Normally, you set cors to an array of domains that you would like to accept requests from. Setting cors to * is generally not recommended, you should instead add the domains to the cors array like so:

    cors: ['http://localhost:3000']
  • default discord avatar
    clhomelast year

    I try to write like cors: ['http://localhost:3000'] before in payload.config.ts,but it`s not work. "*"just for test

  • default discord avatar
    VadBelast year

    Normally, you set cors to an array of domains that you would like to accept requests from. Setting cors to * is generally not recommended, you should instead add the domains to the cors array like so:

    cors: ['http://localhost:3000']

    http:// is not a part of domain, and cors: '*' not working.

  • default discord avatar
    Sandros94last year

    CORS is indeed behaving strangely.
    Currently I need to configure my public url to be without the port number (for deployment reasons), as such I expected my payload.config.ts to be like this:

    import { buildConfig } from 'payload/config';
    import path from 'path';
    import Categories from './collections/Categories';
    import Posts from './collections/Posts';
    import Tags from './collections/Tags';
    import Users from './collections/Users';
    import Media from './collections/Media';
    
    export default buildConfig({
      serverURL: `${process.env.PUBLIC_URL || 'http://localhost'}:${process.env.PAYLOAD_PORT || 3000}`,
      admin: {
        user: Users.slug,
      },
      collections: [Categories, Posts, Tags, Users, Media],
      typescript: {
        outputFile: path.resolve(__dirname, 'payload-types.ts'),
      },
      graphQL: {
        schemaOutputFile: path.resolve(__dirname, 'generated-schema.graphql'),
      },
      ...(process.env.PUBLIC_URL
        ? {
            cors: [(`${process.env.PUBLIC_URL}:${process.env.PAYLOAD_PORT}`)].filter(Boolean),
            csrf: [(`${process.env.PUBLIC_URL}:${process.env.PAYLOAD_PORT}`)].filter(Boolean),
          }
        : {}),
    })

    And add my process.env.PAYLOAD_PORT to the server.ts.

    But no matter what I get cors trying to connect to port 3000 instead of the PAYLOAD_PORT.

    If I leave everything as is and hardcode the full url+port ONLY into serverURL like:

      serverURL: 'https://localhost:8000',

    magically cors start to work as expected, even by leaving the config above.

    3 replies
    default discord avatar
    Sandros94last year

    Looks like webpack initialize payload.config.ts before all the env variables.

    default discord avatar
    LuisFernandoLG11 months ago

    did you find any solution? i noticed that too :(

    default discord avatar
    isaackoz11 months ago

    I could be wrong, but I believe require("dotenv").config?.(); might be required.

    require("dotenv").config?.();
    
    export default buildConfig({
        serverURL: process.env.PAYLOAD_PUBLIC_SERVER_URL,
        cors: [
            process.env.PAYLOAD_PUBLIC_SERVER_URL,
            process.env.PAYLOAD_PUBLIC_SITE_URL,
            "http://localhost:3000",
        ],
        csrf: [
            process.env.PAYLOAD_PUBLIC_SERVER_URL,
            process.env.PAYLOAD_PUBLIC_SITE_URL,
            "http://localhost:3000",
        ],
    // rest of config
    

    Also, if you still have issues, try deleting the .cache and restart it.

  • default discord avatar
    gar-cad12 months ago

    I am constantly getting cors error on mine, regardless of what value i enter.

  • default discord avatar
    slelas6 months ago

    This is still not working properly. Tried all combinations:

    image image

    Only cors: '*' works properly.

    4 replies
    default discord avatar
    remarcable6 months ago

    It seems to me like you are accessing the API that listens at localhost:8080 from another localhost URL with the port :3000.

    Try adding http://localhost:3000 to the CORS option, I suppose it should work then.

    default discord avatar
    remarcable6 months ago

    If I see correctly that your frontend is hosted at http://localhost:3000 and payload is hosted at http://localhost:8080, you need to add those two URLs to the cors array in the config.

    default discord avatar
    dbersan5 months ago

    I'm sorry I must be really dumb, but why TF do you need to add the payload URL to the accepted CORS? You should need to add only the frontend URL, no? I thought it was like this for the past 5 years, no? why do you need to allow the server itself to make requests to itself? I never had to do this before? Why?

    default discord avatar
    remarcable5 months ago

    To clarify this a bit more, here is what I think is happening behind the scenes:

    • The frontend (localhost:3000) is making a request to Payload (localhost:8080)
    • The frontend is running in a browser. The browser makes a preflight request to Payload to check the CORS configuration. CORS will tell the browser if the page making the request (i.e. the "origin" / your frontend, from port 3000) should be allowed to make a request
    • If the server (i.e. Payload) doesn't specify the correct CORS URL, the browser will block the API call because it assumes that this could be a malicious request

    The server probably doesn't make requests to itself, the frontend makes a request to Payload.

    Regarding your comment and my answer above @dhiegomaga, did it work for you after adding both URLs or is one sufficient?

    I think you should be fine without adding the Payload URL to the CORS config. Don't really know why I suggested adding both URLs 🤷 Hope this helps!

  • default discord avatar
    JP-HoneyBadger3 months ago

    Watching, seeing the same issue.

  • default discord avatar
    cgilly2fast3 months ago

    Tried to do this the right way by listing my cors urls in the payload config but didnt work. I am deploying a docker container on a Ubuntu 20 google vm. routing from ports 80 to 3000. I listed my google ip and local host in all relavant variation that made sense and still kept getting these errors when i would go the ip address of the vm.

    Access to fetch at 'http://localhost:3000/api/users/me' from origin 'http://34.70.117.216' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`.
    main.b65538cf9e6cbf009399.js:21 
            
            
           GET http://localhost:3000/api/users/me net::ERR_FAILED
    get @ main.b65538cf9e6cbf009399.js:21
    (anonymous) @ main.b65538cf9e6cbf009399.js:44
    (anonymous) @ main.b65538cf9e6cbf009399.js:44
    iF @ main.b65538cf9e6cbf009399.js:52
    lW @ main.b65538cf9e6cbf009399.js:52
    (anonymous) @ main.b65538cf9e6cbf009399.js:52
    E @ main.b65538cf9e6cbf009399.js:75
    _ @ main.b65538cf9e6cbf009399.js:75
    admin:1 Access to fetch at 'http://localhost:3000/api/payload-preferences/nav' from origin 'http://34.70.117.216' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`.
    main.b65538cf9e6cbf009399.js:21 
            
           GET http://localhost:3000/api/payload-preferences/nav net::ERR_FAILED
    get @ main.b65538cf9e6cbf009399.js:21
    (anonymous) @ main.b65538cf9e6cbf009399.js:44
    (anonymous) @ main.b65538cf9e6cbf009399.js:44
    (anonymous) @ main.b65538cf9e6cbf009399.js:44
    c @ main.b65538cf9e6cbf009399.js:24
    (anonymous) @ main.b65538cf9e6cbf009399.js:24
    (anonymous) @ main.b65538cf9e6cbf009399.js:24
    iF @ main.b65538cf9e6cbf009399.js:52
    lW @ main.b65538cf9e6cbf009399.js:52
    (anonymous) @ main.b65538cf9e6cbf009399.js:52
    E @ main.b65538cf9e6cbf009399.js:75
    _ @ main.b65538cf9e6cbf009399.js:75
    main.b65538cf9e6cbf009399.js:21 
    
           Uncaught (in promise) TypeError: Failed to fetch
        at Object.get (main.b65538cf9e6cbf009399.js:21:29933)
        at main.b65538cf9e6cbf009399.js:44:43049
        at main.b65538cf9e6cbf009399.js:44:43202
        at new Promise (<anonymous>)
        at main.b65538cf9e6cbf009399.js:44:42999
        at c (main.b65538cf9e6cbf009399.js:24:44141)
        at main.b65538cf9e6cbf009399.js:24:44428
        at main.b65538cf9e6cbf009399.js:24:44435
        at iF (main.b65538cf9e6cbf009399.js:52:84118)
        at lW (main.b65538cf9e6cbf009399.js:52:113152)
    
    1 reply
    default discord avatar
    AlvSovereign3 months ago

    Are you using Payload 3? If so, try listing the URLs in the Next.js config file (https://nextjs.org/docs/pages/api-reference/next-config-js/headers#cors) since the payload app is a Next.js Api Route.

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.