+7

Implementing a CORS sample that supports multiple origins using Node.js and Express

Implement

When creating a web application using a REST API or front-end framework, it is not uncommon to be troubled by CORS (Cross-Origin Resource Sharing).

image.png

CORS is a security restriction for JavaScript in web browsers (front-end), which means that, when using AJAX or other methods to make HTTP requests, only requests from the same origin are allowed and requests from different origins will fail due to the CORS restriction. There are no restrictions for HTTP requests from the back-end, but it only applies to requests from the front-end. For more information, please see here: https://developer.mozilla.org/ja/docs/Web/HTTP/CORS

If the same person is making both the REST API and the front-end web application, or if they know that such requests will come in, they may want to ignore the CORS restriction on the API side. For this, it is possible to set up the API to "allow HTTP requests from a specific origin". Specifically, by specifying the origin (https://allowed-origin.com) to be allowed and returning an HTTP response header of Access-Control-Allow-Origin: https://allowed-origin.com, the request source will compare this header content to its own origin and process it normally only if it matches (otherwise it will be an error). It is also possible to specify "allow requests from all origins", and in this case it can be realized by returning an exceptional HTTP response header of Access-Control-Allow-Origin: *.

Now, when developing the front-end side, you may face the following problems:

  1. Run it on http://localhost:3000 while developing or testing.
  2. After development is finished, it will be used in actual operation at https://xxxxx.com.
  3. A REST API will not work unless CORS settings are configured, which is different in both (1) and (2).

When developing, we use a local host such as http://localhost:3000 to check the code, and when in production, we use an internet host such as https://xxxxx.com to access it. This is not a particularly unusual case. In order to run the REST API in both development and production environments, it would be convenient to set up CORS (regardless of whether requests from http://localhost:3000 are allowed or not). However, there is a restriction that only one origin (and not even a regular expression other than *) can be specified in the Access-Control-Allow-Origin header. In other words, it is not possible to specify "allow requests from http://localhost:3000 or https://xxxxx.com" in the Access-Control-Allow-Origin header. Is there any way to work around this and make it possible?

One possible way is to specify Access-Control-Allow-Origin: * during development to allow requests from all origins, but this is also a very vulnerable setting.

I came up with the following method: Prepare an array of allowed origins in advance, and if the request source is included in the allowed origin array, dynamically specify the origin in the Access-Control-Allow-Origin header and return it. If you make it specifically for the Node.js + Express environment, it looks like this:

// app.js
const express = require("express");
const app = express();

app.use(express.Router());

var settings_cors = "CORS" in process.env ? process.env.CORS : "";
app.all("/*", function (req, res, next) {
  if (settings_cors) {
    var origin = req.headers.origin;
    if (origin) {
      var cors = settings_cors.split(" ").join("").split(",");

      // We need to support "*" for cors.
      if (cors.indexOf("*") > -1) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Vary", "Origin");
      } else {
        res.setHeader("Access-Control-Allow-Origin", origin);
        res.setHeader("Vary", "Origin");
      }
    }
  }
  next();
});

app.get("/ping", function (req, res) {
  res.contentType("application/json; charset=utf-8");

  res.write(JSON.stringify({ status: true, message: "PONG" }, null, 2));
  res.end();
});

var port = process.env.PORT || 8080;
app.listen(port);
console.log("server starting on " + port + " ...");

At startup, specify an array of allowed origins (in this example, "http://localhost:3000" and "https://xxxxx.herokuapp.com") as the CORS environment variable, separated by commas.

(sample)$ CORS=http://localhost:3000,https://xxxxx.herokuapp.com node app

This sample (running on port 8080) defines a REST API that responds to a GET /ping request with { status: true, message: 'PONG' }. If the origin of the request is either http://localhost:3000 or https://xxxxx.herokuapp.com, then CORS restrictions can be bypassed by the Access-Control-Allow-Origin header.

It looks like we can set up an API server that can be used in test, staging, and production environments without changing the CORS settings.

The sample source code I provided is here: https://github.com/dotnsf/multicors

Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.

Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.

Momo: NGUYỄN ANH TUẤN - 0374226770

TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí