'How can i get domain name in Nestjs?

Now, i want to get domain name. I don't want hardcode for path return eg: https://mydomain/url-img. My purpose is when i develop in local enviroment, I can return url which like that http://localhost:3000/url-img.



Solution 1:[1]

Your best solution would be to use the dotenv package (or use docker-compose instead) and in your .env file have something like

DOMAIN="http://localhost:3000"

and set it differently in prod. Then in your code you just access it with process.env.DOMAIN and append the /url-img to the domain for the full URL.

Solution 2:[2]

You can use the x-forwarded-proto from the headers and then construct it with a string iterator to form your full domain.

Here is a snippet from my code. ?

  import { Request} from '@nestjs/common';
  import { Request as ExpressRequest } from 'express';

  ...

  @ApiExcludeEndpoint()
  @Get(['api', 'docs', 'playground'])
  @Render('index.hbs')
  docs(@Request() request?: ExpressRequest) {
    const hour = new Date().getHours();
    return {
      schema_url: `${request.headers['x-forwarded-proto'] ?? request.protocol}://${request.headers.host}/swagger-json`,
      theme: hour < 6 && hour > 19 ? 'dark' : 'light'
    }
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jay McDoniel
Solution 2 Vixson