Picture of Brian Love wearing black against a dark wall in Portland, OR.

Brian Love

CORS in Express using TypeScript

A quick walkthrough on configuring CORS in your Express app using TypeScript and the cors middleware.

If you are not familiar with Cross-origin resource sharing (CORS), here is the definition according to wikipedia:

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served.

My use case for CORS is an Angular application that is making REST requests to an API running in Express.js. I’ll be using TypeScript, which will be compiled to ES2015 (ES6) compatible JavaScript that will be executed in Node.js.

Getting Started

We’ll be using Express to serve up some awesome content. I will assume that you have already installed:

First, let’s install our dependencies. I’ll be using the cors middleware. So, let’s install that package as well as the TypeScript definitions:

$ npm install cors --save
$ npm install @types/cors --save-dev

Setting it up

Let’s dive into the server.ts file where we will be enabling and configuring CORS in our Express app:

import * as cors from 'cors';

//get router
var router = express.Router();

//options for cors midddleware
const options: cors.CorsOptions = {
  allowedHeaders: [
    'Origin',
    'X-Requested-With',
    'Content-Type',
    'Accept',
    'X-Access-Token',
  ],
  credentials: true,
  methods: 'GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE',
  origin: API_URL,
  preflightContinue: false,
};

//use cors middleware
router.use(cors(options));

//add your routes

//enable pre-flight
router.options('*', cors(options));

Let’s go through the code above:

Here it is in action:

Email template screen shot

Note the values of the following headers:

We now have CORS configured for our REST API. Now, it’s time to build something awesome!