CORS configuration ineffective.

default discord avatar
clhome
10 months ago
3 4

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

  • default discord avatar
    clhome
    10 months ago

    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
    Payload Team
    10 months ago

    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
    clhome
    9 months ago

    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
    VadBe
    9 months ago

    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
    Sandros94
    9 months ago

    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
    Sandros94
    9 months ago

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

    default discord avatar
    LuisFernandoLG
    6 months ago

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

    default discord avatar
    isaackoz
    6 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-cad
    7 months ago

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

  • default discord avatar
    slelas
    last month

    This is still not working properly. Tried all combinations:

    image image

    Only cors: '*' works properly.

    4 replies
    default discord avatar
    remarcable
    last month

    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
    remarcable
    last month

    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
    dhiegomaga
    last week

    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
    remarcable
    last week

    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!

Open the post
Continue the discussion in GitHub
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

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