Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Manage Cross-Origin Resource Sharing In A Node With Hapi Application

To continue down my path of solving the worlds cross-origin resource sharing (CORS) problems, I wanted to adventure into Hapi, a Node.js framework that I’ve been heavily using lately. If you’re not familiar with cross-origin resource sharing, it is something that frequently comes up when you try to use front-end JavaScript to access content from another host or port.

Previously I had written about exploring CORS in an Express with Node.js application. While Express is probably the most popular framework, it certainly isn’t the only framework, which is why we’re going to take a look at CORS in Hapi.

Creating Boilerplate Code for a Node.js with Hapi Application

Before we take a look at enabling CORS, let’s get a sample project created. From the command line, execute the following:

npm init -y

The above command will create a package.json file wherever the command line path is pointing. The next step is to download any project dependencies. From the command line, execute the following:

npm install hapi --save

The above command will download Hapi to the project. Unlike with the Express alternative that I wrote about previously, no additional middleware is required.

Create an app.js file within your project and include the following code:

const Hapi = require("hapi");

const server = new Hapi.Server();

server.connection({ "host": "localhost", "port": 3000 });

server.route({
    method: "GET",
    path: "/",
    handler: (request, response) => {
        response("Hello World");
    }
});

server.start(error => {
    if(error) {
        throw error;
    }
    console.log("Listening at " + server.info.uri);
});

The above code will initialize Hapi and start a server on localhost. As of right now, browser-made API calls will result in errors. We’re going to correct this.

Enabling Cross-Origin Resource Sharing in the Application

By default Hapi has CORS disabled. We need to enable it so that our browser-based applications can consume data from a different host or port.

Within the app.js file, include the following:

server.connection({
    "host": "localhost",
    "port": 3000,
    "routes": {
        "cors": true
    }
});

By changing the connection configuration to the above, we are enabling CORS and accepting pretty much everything that hits the server.

If you need to harden what is allowed via cross-origin resource sharing, the cors property can also accept an object, rather than a boolean. For example, it can be changed to look like the following:

server.connection({
    "host": "localhost",
    "port": 3000,
    "routes": {
        "cors": {
            origin: ["*"],
            headers: ["Accept", "Content-Type"]
            additionalHeaders: ["X-Requested-With"]
        }
    }
});

More on the subject can be found in the official Hapi API documentation.

Conclusion

You just saw how to enable and configure cross-origin resource sharing (CORS) in a Node.js application that uses Hapi as its framework. Enabling and configuring CORS is required when using browser-based JavaScript and backends that operate on different hosts or ports.

To see how to enable and configure CORS in an Express Framework application, check my tutorial here.

If you don’t have access to the backend, you can also force the browser to ignore CORS. Bypassing CORS via the browser can be seen in a previous article I wrote on the subject.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

Search

Follow Us

Support This Site