How to get FullURL and Domain with NestJS?
In this tutorial, We will look into how to get Full URL in NestJS controller with code examples.
How to get Full URL and hostname in NestJS Controller
To get Full Url in NestJS controller, Please follow below steps
- First, Import Request into controller
import {Request} from 'express';
- Next, Inject
Requestobject into Controller method with type@Reqdecorator
@Get("url")
getUrl(@Req() req: Request): void {}
- req object holds request header and body details
- req.protocol : gives
httporhttpsprotocol of calling URL - req.get(‘Host’): returns hostname of url
- req.originalUrl: returns url excluding domain and protocal
- req.protocol : gives
const protocol = req.protocol;
const host = req.get('Host');
const originUrl = req.originalUrl;
const fullUrl = protocol + host + originUrl;
Here is an complete code example
import { Controller, Get, Req } from "@nestjs/common";
import { Request } from "express";
@Controller("api")
export class AppController {
constructor() {}
@Get("url")
getUrl(@Req() req: Request): void {
const protocol = req.protocol;
const host = req.get("Host");
const originUrl = req.originalUrl;
const fullUrl = protocol + host + originUrl;
console.log(fullUrl);
}
}
It prints to console
http://localhost:3000/api/url
