Skip to content

Commit e8fe17c

Browse files
committed
feat(core): add method to get server address
1 parent 6c3f188 commit e8fe17c

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

packages/common/interfaces/nest-application.interface.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ export interface INestApplication extends INestApplicationContext {
4343
callback?: () => void,
4444
): Promise<any>;
4545

46+
/**
47+
* Returns the url the application is listening at, based on OS and IP version. Returns as an IP value either in IPv6 or IPv4
48+
*
49+
* @returns The IP where the server is listening
50+
*/
51+
url(): string;
52+
4653
/**
4754
* Starts the application (can be awaited).
4855
*

packages/core/nest-application.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import { MiddlewareModule } from './middleware/middleware-module';
2525
import { NestApplicationContext } from './nest-application-context';
2626
import { Resolver } from './router/interfaces/resolver.interface';
2727
import { RoutesResolver } from './router/routes-resolver';
28+
import { platform } from 'os';
2829

2930
const { SocketModule } = optionalRequire(
3031
'@nestjs/websockets/socket-module',
@@ -237,6 +238,40 @@ export class NestApplication extends NestApplicationContext
237238
});
238239
}
239240

241+
public url(): string {
242+
const address = this.getHttpServer().address();
243+
if (typeof address === 'string') {
244+
if (platform() === 'win32') {
245+
return address;
246+
}
247+
const basePath = encodeURIComponent(address);
248+
return `${this.getProtocol()}+unix://${basePath}`;
249+
}
250+
let host = this.host();
251+
if (address && address.family === 'IPv6') {
252+
if (host === '::') {
253+
host = '::1';
254+
} else if (host === '0.0.0.0') {
255+
host = '127.0.0.1';
256+
}
257+
} else {
258+
host = '127.0.0.1';
259+
}
260+
return `${this.getProtocol()}://${host}`;
261+
}
262+
263+
private host(): string | undefined {
264+
const address = this.getHttpServer().address();
265+
if (typeof address === 'string') {
266+
return undefined;
267+
}
268+
return address && address.address;
269+
}
270+
271+
private getProtocol(): 'http' | 'https' {
272+
return this.appOptions && this.appOptions.httpsOptions ? 'https' : 'http';
273+
}
274+
240275
public setGlobalPrefix(prefix: string): this {
241276
this.config.setGlobalPrefix(prefix);
242277
return this;

0 commit comments

Comments
 (0)