Cross Origin Resource Sharing (CORS) across Subdomains
Asked Answered
W

3

15

Suppose I have an app at www.example.com (a)

If my resource is at www.someotherdomain.com (b) and I make an AJAX call from (a) to (b) then CORS rules would apply.

However if my resource is located at api.example.com (c) then one would expect to avoid CORS when making an AJAX request from (a) to (c) - however, I have found this not to be the case.

CORS rules still apply when making requests across subdomains - is this true?

Is there away around this rule (without using JSONP)?

I cant imagine that all requests made between www.amazon.com and resource.amazon.com, for instance, are always CORS requests. Managing the headers and preflight request/response seems tedious & costly at scale.

Anything Im missing here?

Weld answered 21/11, 2017 at 4:47 Comment(3)
sub domain is a different origin. CORS is actually relatively easy to deal with, unless you wanted to get super specific with it and only allow it on particular endpoints for particular origins, but even that isn't all that difficult.Subbasement
Thank you. I agree that it isnt too difficult but it seems like the preflight requests can degrade performance at scale (suppose my app makes 1000 requests, ignoring performance improvements due by changing request architecture). is this not a significant issue?Weld
I don't think the preflight gets sent with every request. If you for example sent a dozen in a row there would only be oneSubbasement
Z
8

CORS is for a single set of protocol:domain:port, or null, or *. See https://www.w3.org/TR/cors/#access-control-allow-origin-response-header.

So the answer to your question is, Yes, CORS rules will still apply to your subdomains.

Zinn answered 21/11, 2017 at 4:53 Comment(0)
S
3

One note - you can make a call from (c) to (a) using the document.domain method outlined in the top answer here

Ways to circumvent the same-origin policy

Simmons answered 21/3, 2019 at 11:28 Comment(0)
B
0

A bit late, but to anyone still needing the answer, here it is:

You can use regex when setting up CORS. So, for example, covering all subdomains:

import * as express from "express";
import * as cors from "cors";

const app = express();

app.use(cors({
  origin: [/example\.com$/],
}));

Will cover: example.com, sub.example.com, www.example.com,...

Bridgehead answered 23/7 at 10:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.