Express CORS Middleware

Learn via video courses
Topics Covered

Overview

Internet browsers usually block access to unidentified websites from your services and application programming interfaces. Implementing this enables your server to share its resources solely with clients who reside in the same domain as yours and nobody else. There are times, though, when you might want to let down this guard or exert more control over which websites get access to your server's resources. The solution to such situations is to implement express cors in Node.js on your server.

What is CORS?

The abbreviation CORS stands for "Cross-Origin Resource Sharing". CORS, an HTTP-header-based mechanism implemented by browsers, enables a server or API (Application Programming Interface) to specify any origins (other than its own) from which the unknown origin can access and load resources. These origins can differ in terms of protocol, hostname, or port.

Cross-origin resource sharing (CORS), to put it simply, enables AJAX requests to bypass the Same-origin policy and access resources from distant servers. I'll demonstrate how to make express cors in this article. Many apps and websites in use today rely on APIs to access various resources. The weather, time, and fonts are a few of the well-liked APIs. Additionally, there are servers that house these APIs and guarantee the delivery of data to websites and other endpoints. Consequently, making cross-origin calls is a common use case for contemporary online applications.

Consider gaining access to photos, videos, iframes, or scripts on a different server. This indicates that a separate origin or domain is being used by the website to access resources. A request to such external origins might not succeed while developing an application to offer up these resources with Express. CORS can manage cross-origin requests in this situation.

How CORS Works?

An API is a protocol that allows two programs to interact with one another. This indicates that other clients and servers consume these API resources.

Here are two instances:

API resources

Suppose the origin of both the client and the server is the same. In this case, getting access to the resources will work. The server that processes the request is the one from which you are attempting to access resources.

How express cors works OUTPUT 2

Now let us suppose the client and server have separate origins, i.e., they obtain resources from distinct servers. Any attempt to access a resource on the other server will fail in this situation.

The browser should be concerned about security here. To neutralize this technique and open access to these resources, CORS is activated. Access-control-allow-sources, a response header that express cors will include, will list the approved origins. We transmit the appropriate headers because of CORS.

As a result, the response from a public server handling a public API will include a CORS-related header. This header will be examined by the client machine's browser before determining if it is secure to send the requested answer to the client.

Setting up CORS with Express

Let's build a simple GET response endpoint for an Express HTTP server. Start your straightforward express server project by using npm init -y after making sure Node.js runtime is installed. You require the cor package offered by the Node.js NPM registry in order to use express cors within a Node.js application. Use the command below to install express cors together with the following additional packages.

Using CORS in Express

Simple Usage

Enable CORS for a Single Route

Configuring CORS

Configuring CORS w/ Dynamic Origin

This module allows you to dynamically validate the origin by utilizing a function specified by the origin parameter. This method will be supplied a string representing the origin (or undefined if no origin is specified in the request) and a callback with the signature callback(error, origin).

The origin parameter to the callback can be any value permitted by the middleware's origin option, except a function. More information on all of the potential value types may be found in the setup options section.

This function is intended to enable the dynamic loading of permitted origins from a backend data source, such as a database.

Enabling CORS Pre-Flight

Certain express cors queries are deemed 'complicated' and necessitate a first OPTIONS request (dubbed the "pre-flight request"). A 'complex' express cors request employs an HTTP verb other than GET/HEAD/POST (for example, DELETE) or includes custom headers. To enable pre-flighting, create a new OPTIONS handler for each route that you want to support :

Note : Pre-flight requests are already handled for all routes when using this middleware as an application-level middleware (for example, app.use(cors())).

Configuring CORS Asynchronously

Configuration Options

  • origin : Access-Control-Allow-Origin (express cors) header configuration for origin. Potential values :
    • Boolean : Set origin to true to enable CORS or false to disable CORS and reflect the request origin as specified by req.header('Origin').
    • String : Set the origin to a particular origin. Using "http://abc.com" as an example, only requests coming from that address will be accepted.
    • RegExp : Set the request origin to a regular expression pattern that will be tested. The request origin will be reflected if it matches. The pattern /abc.com$/, for instance, will reflect any request originating from an origin with the prefix "abc.com".
    • Array : Set origin to an array of legal origins using the Array keyword. Origins may either be Strings or RegExps. For instance, ["http://abc.com", /.example2com$/] will accept any requests coming from either "http://abc.com" or a subdomain of "example2.com".
    • Function : Set the origin to a function that implements some unique logic. The function's first and second parameters are the origin of the request and a callback, where the origin is a non-function value for the origin option.
  • methods : the Access-Control-Allow-Methods (express cors) header is configured. Expects either an array (ex: ['POST', 'GET', 'PUT']) or a string with commas between the words (ex: 'POST, GET, PUT').
  • allowedHeaders : Access-Control-Allow-Headers (express cors) header configuration is done via allowedHeaders. Expects a string (for example, "Content-Type, Authorization") or an array (for example, "Content-Type," "Authorization"). If not supplied, it defaults to mirroring the access-control-request-headers specified in the request.
  • exposedHeaders : Access-Control-Expose-Headers CORS header configuration is done via exposedHeaders. the string "Content-Range,X-Content-Range" or an array "['Content-Range', 'X-Content-Range']" should be comma-delimited. No custom headers are accessible if not supplied.
  • credentials : Sets the CORS Access-Control-Allow-Credentials header. If true, the header is passed; otherwise, it is not.
  • maxAge : Sets the CORS Access-Control-Max-Age header parameters. If set to an integer, the header will be sent; otherwise, it won't.
  • preflightContinue : Give the following handler the (express cors) preflight answer.
  • optionsSuccessStatus : Since certain legacy browsers (IE11, several SmartTVs) choke on 204, it provides a status code to use for successful OPTIONS requests.

Restricting Allowed Hosts

You may use the origin parameter to limit AJAX access to a single origin :

Use a function rather than a string as the original value if you'd want to have a list of permitted origins :

If you send a new request to the server, you'll note that the Access-Control-Allow-Origin header now includes the origin of the request : Access-Control-Allow-Origin : http://localhost:3000

Sending Custom Headers

Only six response headers are available by default via express cors, which are Cache-Control, Pragma, Expires, Last-Modified, Content-Language and Content-Type.

The exposedHeaders option can be used to expose additional headers :

Your server answers now come with an extra Access-Control-Expose-Headers header, as you can see :

Access-Control-Expose-Headers: Content-Length,X-Foo,X-Bar

HTTP Sessions Over CORS

A tried-and-true method for handling online authentication is HTTP sessions. However, HTTP Sessions rely on cookies, which are not often delivered via CORS.

Two actions must be taken to allow HTTP cookies across express cors :

  • Set the credentials options to true.

By doing this, the response will also contain the following Access-Control-Allow-Credentials header : Access-Control-Allow-Credentials: true

  • Ensure that the withCredentials attribute is set to true before submitting the AJAX request.

Conclusion

  • Express can quickly and easily add CORS functionality if we utilize the cors library.
  • Cross-origin resource sharing (express cors), to put it simply, enables AJAX requests to bypass the Same-origin policy and access resources from distant servers.
  • An API is a protocol that allows two programs to interact with one another.
  • HTTP Sessions rely on cookies, which are not often delivered via express cors.
  • Only six response headers are available by default via express cors, which are Cache-Control, Pragma, Expires, Last-Modified, Content-Language and Content-Type.
  • The exposedHeaders option can be used to expose additional headers.