DEV Community

Cover image for Cross-Origin Resource Sharing(CORS). CORS middleware Setup.
Pranit Karkera
Pranit Karkera

Posted on

Cross-Origin Resource Sharing(CORS). CORS middleware Setup.

What is CORS?

CORS stands for Cross-Origin Resource Sharing. It is a security feature implemented by web browsers to prevent web pages from making requests to a different domain than the one that served the web page. This is known as the Same-Origin Policy. Without CORS, a web page hosted on https://example.com cannot make an API request to https://api.anotherdomain.com.

CORS allows servers to specify who can access their resources and under what conditions. It does this by adding specific HTTP headers to the server's responses.


CORS in Your Example

In your code, you are using the cors middleware in an Express.js application to enable CORS. Here's a breakdown of how it works:

CORS Middleware Setup

const corsOptions = {
  origin: "*",
  credentials: true,
  optionSuccessStatus: 200,
};

app.use(cors(corsOptions));
Enter fullscreen mode Exit fullscreen mode
  • origin: "*": This allows requests from any domain. The  is a wildcard that means "all origins are allowed." This is useful for public APIs but should be used cautiously in production, as it can expose your API to security risks.
  • credentials: true: This allows the server to accept credentials (e.g., cookies, authorization headers) from the client. If the client includes credentials in the request (e.g., with withCredentials: true in an XMLHttpRequest or Fetch API call), the server must respond with the Access-Control-Allow-Credentials: true header.
  • optionSuccessStatus: 200: This sets the HTTP status code for OPTIONS requests (preflight requests) to 200. By default, some browsers expect a 204 status code for preflight requests, but this setting ensures compatibility.

How CORS Works in Your Application

CORS Request Flow

When a client (e.g., a browser) makes a request to your server, the following happens:

  1. Preflight Request (if applicable):
    • For certain types of requests (e.g., those with custom headers or non-standard HTTP methods), the browser sends an OPTIONS request to the server to check if the actual request is allowed.
    • The server responds with CORS headers (e.g., Access-Control-Allow-OriginAccess-Control-Allow-Methods, etc.) to indicate whether the request is permitted.
  2. Actual Request:
    • If the preflight request is successful, the browser sends the actual request (e.g., GETPOST, etc.).
    • The server processes the request and includes the appropriate CORS headers in the response.

CORS Headers in Responses

When the cors middleware is used, it automatically adds the following headers to responses:

  • Access-Control-Allow-Origin: *: Allows requests from any origin.
  • Access-Control-Allow-Credentials: true: Allows credentials to be included in requests.
  • Access-Control-Allow-Methods: Specifies which HTTP methods are allowed (e.g., GETPOST, etc.).
  • Access-Control-Allow-Headers: Specifies which headers can be used in the actual request.

Example Scenario

Suppose your Express server is running at http://localhost:3000, and a web application hosted at https://example.com tries to make a request to your API.

  1. The browser sends a request to http://localhost:3000/api/products.
  2. The server responds with the appropriate CORS headers:

    Access-Control-Allow-Origin: *Access-Control-Allow-Credentials: true
    
  3. The browser checks these headers and allows the response to be accessed by the web application at https://example.com.


Key Points to Remember

  1. Security Considerations:
    • Using origin: "*" is convenient but can expose your API to cross-site request forgery (CSRF) attacks. In production, it's better to specify trusted origins explicitly, e.g., origin: "https://example.com".
  2. Credentials:
    • If credentials: true is set, the Access-Control-Allow-Origin header cannot be . You must specify a specific origin.
  3. Preflight Requests:
    • Not all requests trigger a preflight request. Simple requests (e.g., GET or POST with standard headers) do not require a preflight.
  4. Testing CORS:
    • You can test CORS behavior using tools like Postman or by running a frontend application and inspecting network requests in the browser's developer tools.

Example of a More Secure CORS Configuration

If you want to restrict access to specific domains, you can modify the corsOptions like this:

const corsOptions = {
  origin: "https://example.com", // Allow only this domain
  credentials: true,
  optionSuccessStatus: 200,
};
Enter fullscreen mode Exit fullscreen mode

This ensures that only requests from https://example.com are allowed, improving security.


By using the cors middleware in your Express application, you enable cross-origin requests while controlling access to your API resources.


More information about javascript array methods can be found in the React docs:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Leave comment if you have any questions or feedback.

Top comments (0)