Nest: Global route for all controllers

Created on 8 May 2017  路  7Comments  路  Source: nestjs/nest

Hi,

is there any suggested way how to set a "global" route for all controllers?

For example, I want to define this route:
/api/

for my controllers:

@Controller('user')
export class UserController

@Controller('customer')
export class CustomerController

with the following result:

/api/user
/api/customer

Thank you

type

Most helpful comment

Hi @jezikk,
Since version 2.1.0 you can use setGlobalPrefix(prefix: string) method. Example:

const app = NestFactory.create(ApplicationModule);
app.setGlobalPrefix('api');

All 7 comments

I was wondering about the same. In express you can prepend paths by using the Router, and then:

app.use('/a-route', aModule)

Is this existing in nest, or is a feature request?

Very interesting, that library allows both global prefixes and per-controller prefixes, such as:

@Controller("/users")
export class UserController {
    // ...
}

Hi @jezikk,
Since version 2.1.0 you can use setGlobalPrefix(prefix: string) method. Example:

const app = NestFactory.create(ApplicationModule);
app.setGlobalPrefix('api');

Should this work with swagger?

import {NestFactory} from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

// ....
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('v1');
const options = new DocumentBuilder()
      .setTitle('title')
      .setDescription('API description')
      .setVersion('0.1')
      .addTag('tag')
      .build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('docs', app, document);

// ....

This doesn't add v1 as prefix in the documentation reflected on /docs/, but is reflected to the api, so I have to call /v1/... to get the endpoint.

Is this a bug?

@flogvit

// document
    .setBasePath('v1')

As you can create multiple swagger documents (like, for every API version) it makes sense that it is no automatically derived from app

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings