How to get the base url variable on a deployed Heroku node app

Backend

This checks if you are in production or development mode and assigns the according url depending on the mode.

const production  = 'https://examplePage.com';
const development = 'http://localhost:3000/';
const url = (process.env.NODE_ENV ? production : development);

Explanation: process.env.NODE_ENV will resolve to undefined if you are running on localhost production mode. And return production if you have deployed the app production mode.

Note: just because you have deployed the app doesn't necessarily mean you have changed the NODE_ENV


Frontend

Make use of the javascript window to extract the url

const url = window.location.origin;


You can use Base URL in JavaScript

// This article: // https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript

var base_url = window.location.origin; // "http://stackoverflow.com"

var host = window.location.host; // stackoverflow.com

var pathArray = window.location.pathname.split( '/' ); // ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]