How to add cors protection to an express application

Published on January 17, 2019 - Tagged: #devops #nodejs

Follow me on twitter for more posts like this

Cors protection is a recommended security configuration for any api. It protects your customers from unexpected attacks by blocking websites you haven’t approved.

If you have a devOps team they will handle this for you. But if you are a single maker with an application on Heroku and front end on Netlify you need to implement this yourself.

Like most things in express, there’s a package you can install to add cors protection to your application and with a tiny bit of configuration you’ll be set.

First install the package (https://www.npmjs.com/package/cors)

> yarn add cors

Add a new file to your application in /middleware

import cors from 'cors'

const starterCorsProtection = () => {
  const whitelist = getList()
  const corsOptions = {
    credentials: true,
    optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
    origin: whitelist,
  }

  return cors(corsOptions)
}

const getList = (): string[] => {
  const corsSetting = process.env.CORS_ALLOWED_HOSTS || ''
  return corsSetting.split(',')
}

export default starterCorsProtection

Here I have a getList() method that checks your environment for a list of urls to allow.

The environment setting (in .env file) looks like this for my local host for example.

CORS_ALLOWED_HOSTS="http://localhost:3000, https://localhost:3000"

It might look like this for production

CORS_ALLOWED_HOSTS="https://www.darraghoriordan.com"

The cors() method takes an options object and the configuration is as follows.

  • “credentials: true” sets the Access-Control-Allow-Credentials header. This lets us use credentials on ajax requests.
  • “optionsSuccessStatus: 200” helps cors works on more devices.
  • “origin: whitelist” sets the list of allowed urls to the list we set on getList().

Now import the starterCors in your express configuration. Here I use it on every route with “app.use(starterCors);” You also need to specifically use it in the options methods so DELETE requests work.

const starterCors = starterCorsConfiguration()
app.use(starterCors)
app.options('*', starterCors)

You can see this in action on my starter source code @ https://gitlab.com/darragh.oriordan/starter/tree/master

Darragh ORiordan

Hi! I'm Darragh ORiordan.

I live and work in Sydney, Australia building supporting happy teams that create high quality software for the web.

I also make tools for busy developers! Do you have a new M1 Mac to setup? Have you ever spent a week getting your dev environment just right?

My DevShell tooling will save you 30+ hours configuring your dev environment with all the best modern tools. Get it here

https://darraghoriordan.gumroad.com/l/devshell


Read more articles like this one...

List of article summaries

#devops

Extract user profile attributes from an Azure ADB2C tenant using the Microsoft Graph API

I had to retrieve a list of users from an Azure Active Directory B2C instance today. I thought I could just go through the Azure UI but that’s limited to short pages of data and limited attributes.

There is a CSV export provided on the UI but you won’t get the required identity objects in the csv output if you need a user’s signin email address.

I had to use the Microsoft Graph Api to get what I needed. This is a bit hacky but it does the trick!

#devops

Force restart your Azure App service site and host

Sometimes your Azure App service host will need to be restarted. You can do this but it’s hidden away in the Azure resource manager site. Here’s how to find it!

#devops

Scheduling a feature toggle using no-code with Azure Logic Apps

I use launch darkly to toggle features on an app. There is one third-party dependency that has regular scheduled maintenance and I need to toggle the feature on and off on schedule.

Launch Darkly has built in scheduling to handle this scenario but you have to be on the enterprise plan to use it. The enterprise plan is too expensive to upgrade to for scheduling alone so I needed to find a different way to automate this.

#frontend-development

Avoid rebuild of React App in every CI stage

If you have a react app you can use env vars like REACT_APP_MY_ENV_VAR in your application and React will automatically pull them in to your app when you build the production application.

This is very useful but if you have variables that change for each environment and your application build takes a long time, you might want to avoid building unnecessarily in CI. For example you might have a QA environment and a Staging environment that have different configuration.

We type-check our code on each build and that was taking 5 minutes+ to build each environment so we had to make it faster. We changed our app from using REACT_APP env vars to using a configuration file that we could quickly write to using CI.

Our CI system is Azure DevOops so the CI scripts here are specifically for Azure DevOps but they apply to most CI systems with small changes.

The real work happens in a Node.js script that would work anywhere.