Multi-tenant Applications - Setting up Custom Domains on Localhost with Nextjs

Posted by: Ganesh Pawar

Multi-tenancy from the sub-domain / domain name perspective is very common these days as they are customer friendly and provide a sense of ownership to them. One of the challenges mainly for the developers is to simulate / replicate multi tenancy on their local machines in-order to validate and build behaviors that are dependent on the same - eg - Auth, architecture tenancy, DBs etc.

Example domain setups will look something like this -

We will explore this very use case using NextJS. This blog assumes you have some understanding of NextJS and are comfortable with basic CLI tools.

The first step is, you have to pass the hostname and port parameters in the `next dev` command. You can read more about the parameters in the documentation. We will pass “dev-example.com” as the hostname and “80” as the port. Port 80 is the default popular port to run the HTTP sites. One thing to remember is that ports below 1024 are reserved for operating systems so you might need to run the “yarn dev” command with admin/root privilege.

Update dev script:

The second step is to update the hosts configurations. The file path varies according to the configured OS. In macOS it is situated in `/etc/hosts` and in Windows, it is `c:\Windows\ System32\Drivers\etc\hosts`. To write to this file an admin/root privilege is required.

Run the following command:

Later add an entry for your domain in hosts file.

You can add multiple entries to the hosts file. For example, a subdomain entry will look like this.

`127.0.0.1 subdomain.dev-example.com`

If all the above steps were performed indubitably, you can visit the site at “dev-example.com” and verify the production level functionality directly from your local development environment.

Use cases are:

  1. Verify the production functionality upfront on the local machines before deployments.

  2. Run site on a subdomain for example a multi-tenant application.

  3. The focus is entirely on the production environment without the requirement for functional checks like `isLocalhost`

  4. In most scenarios, cookies work differently on localhost and deployed sites. With such a customizable domain setup, you don’t have to worry anymore.

AccelerateBSi uses cookies to deliver superior functionality and to enhance your experience of our website. Continued use of this site indicates that you accept this policy.