Skip to content

Start an Ngrok instance on express app start

Why use Ngrok on an express app?

Sometimes when testing our express app we need to be able to receive payloads from other domains, this can be complicated because our express app is only available in our localhost, for example we want to test webhook payloads received from other services like Stripe

Getting started

First we need to create a new folder an initialize a node project

mkdir ngrok-express-app
cd ngrok-express-app
npm init -y

Installing npm modules

This is a list of all the packages needed and the reason why we will install them:

"express" (npm install express): Simplifies the creation of RESTful APIs 
using Node
"ngrok" (npm install ngrok): Node.js wrapper for the ngrok client
npm i express ngrok

Initializing server

Now we will create our express server, first create an app.js file on the base of the project, this file will contain the initialization of our express app

// ./app.js

const express = require("express");

// Initialize express app
const app = express();

// Converts incoming JSON data to objects
app.use(express.json());

// Basic route to test that the server is working
app.get("/health", (req, res) => {
    res.status(200).send('Working');
})


module.exports = app;

finally create a new file called index.js on the base of the project. We will use the app from above to listen for new requests and create a Ngrok tunnel on app start you could also use env variables to only initialize Ngrok if the environment is dev or local

// ./index.js

const ngrok = require('ngrok');
// Import app from "./app file
const app = require("./app");

// Port that will be uses to listen to requests
const port = process.env.PORT || 3015;

(async function() {
    console.log("Initializing Ngrok tunnel...");

    // Initialize ngrok using auth token and hostname
    const url = await ngrok.connect({
        proto: "http",
        // Your authtoken if you want your hostname to be the same everytime
        authtoken: "",
        // Your hostname if you want your hostname to be the same everytime
        hostname: "",
        // Your app port
        addr: port,
    });

    console.log(`Listening on url ${url}`);
    console.log("Ngrok tunnel initialized!");
})();

/**
 * Listen on port 3015
 */
app.listen(port, () => {
    console.log(`App listening on port ${port}!`);
});

In order to use the same hostname everytime you need to create a Ngrok account, they have a free tier, you need to get your authtoken and your domain from the section shown in the pictures below

Ngrok auth token

Ngrok domain

Testing

Start your app with "node index.js" and you will se in the console logs that the ngrok tunnel was initialized and sending request to the ngrok endpoint will redirect them to our localhost

GitHub repository

In this repository https://github.com/obravocedillo/NgrokExpressApp you can find the code.