Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Thu Mar 16 2023

How to setup CORS on a Node js express server

In this article, we will briefly go through how to setup a basic NodeJs server with express, and give it some CORS restrictions.

What is CORS?

So, before we jump in to the code. Let's briefly just discuss what CORS is, and how it is working. So CORS stands for Cross-Origin Resource Sharing, and it is basically used for browsers checking whether an origin is allowed to gain access to a servers response, other than its own origin. E.g, if you have a website called webshop.com and you have an API with some business logic, you probably have the server hosted on the same URL, or on a subdomain, like api.webshop.com. By default, no other origin but the same, will be able to read the response from the server. So if webshop-2.com makes a request, it will fail.

However, this can be solved by setting some rules on the server, to tell the browser which origins are allowed to read the responses. Which we will cover in this post.

To read more details about CORS, visit mozilla developer page.

Prerequisites

  • Visual code or similar text editor
  • npm
  • Node

Let's start

Let's start with creating the actual project.

Installing dependencies

  • Type npm init in your terminal and follow the steps
  • Type npm install express in your terminal for getting express
  • Type npm install cors for getting the middleware we are going to use

Creating our server

  • Create a file called index.js in the root of your folder.

Now lets write some code:

// Import our dependencies const express = require("express"); const cors = require("cors"); const app = express(); // Specify our allowed origins const allowed = ["https://webshop.com, https://webshop-2.com, http://localhost:3000"]; // Setting up CORS options const options = { origin: (origin, callback) => { if (allowed.indexOf(origin) === -1) { return callback(new Error("Origin not allowed"), false); } return callback(null, true); } }; // Adding the middleware app.use(cors(options)); // Setting up an example endpoint app.get("/ping", (req, res) => { res.json({ msg: "pong" }); }); // Start the server app.listen(80, function () { console.log("Web server listening on port 80"); });

That is it. Now our server will only accept request from either https://webshop.com, https://webshop-2.com or http://localhost:3000. All other origins will receive an error like origin has been blocked by CORS policy.

  • Start the server by typing node index.js and you should be able to test your endpoint.

Outro

So, this was a super simple example and there is a ton of more reading and exploring to be done regarding this topic. For this tutorial, we will end here. But we will do more advanced example in the future and post it here on the site. I hope you enjoyed and found this post useful!

signatureThu Mar 16 2023
See all our articles