Setup for a NestJS application that uses Swagger, built with ncc
(based on my Node NestJS TypeScript Starter project)
Make sure that all relevant dependencies are installed. We need ALL the Swagger-related dependencies, even if we don't actually use them. Weird, I know.
So, within your package.json
file:
{
"dependencies": {
+ "@nestjs/swagger": "4.5.x",
+ "fastify-swagger": "2.5.x",
+ "swagger-ui-express": "4.1.x"
}
}
Right now, we can navigate to the Swagger page (at http://localhost:3000/swagger) but we get a bunch of errors telling us that static assets (stylesheets, images, ...) couldn't be fetched properly.
ncc
is very intelligent - it not only bundles up all imports but it also recognizes files being read by the application during runtime
(e.g. via fs.readFile
) and copies them over into the build output folder (specifically, into the build/static
folder). The
NestJS Swagger implementation relies on
Swagger UI Express which itself - sadly - reads stuff from the file system during
runtime, such as HTML templates (see Issue #114). So, ncc
will copy
those files over into our build/static
folder. This, however, is something our application currently does not expect.
To fix the issue, we tell our NestJS application to serve the files from within the build/static
folder when requesting them from the
/swagger
URL. So within your main.ts
file:
// Create application
- const app: INestApplication = await NestFactory.create(AppModule);
+ const app: NestExpressApplication = await NestFactory.create(AppModule);
// Configure Swagger
const options = new DocumentBuilder()
.setTitle("Hello World API - Swagger")
.setDescription("REST API description")
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup("/swagger", app, document);
+ // WORKAROUND:
+ // We serve the "static" folder (generated by "ncc") behind the "/swagger" URL so that all Swagger UI assets get fetched properly
+ app.useStaticAssets(join(__dirname, "/static"), {
+ prefix: "/swagger"
+ });
Now, Swagger is ready and running at http://localhost:3000/swagger.
The following commands are available:
Command | Description | CI |
---|---|---|
npm start |
Creates a development build, running in watch mode | |
npm run build |
Creates a production build | ✔️ |
npm run start:build |
Runs a production build | |
npm run test |
Executes all unit tests | ✔️ |
npm run test:watch |
Executes all unit tests, running in watch mode |
Note that linters are not part of this template, you might want to add and configure them yourself!
The build
command will output the result into the build
folder, the application itself will be put at build/index.js
. The test
coverage will be put into the coverage
folder.