Using the EJS template engine with NestJS is not a common practice, as NestJS is primarily designed for building APIs and aligns better with decoupled frontend-backend architectures. However, if you need to use EJS as a server-side template engine to render HTML within NestJS, you can follow these steps:
-
Install the required dependencies: First, install the
ejspackage as a project dependency.bashnpm install ejs -
Configure NestJS to use EJS: In your NestJS application, configure the
ViewEngineto use EJS. This is typically done in themain.tsfile.typescriptimport { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import * as express from 'express'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.use(express.static('public')); // If you have static files (e.g., CSS, JavaScript, images). app.setViewEngine('ejs'); // Set EJS as the template engine. await app.listen(3000); } bootstrap(); -
Create EJS template files: In your project directory, create a folder to store EJS template files (e.g.,
views), and create EJS template files within it (e.g.,index.ejs).shell/src /views index.ejsIn the
index.ejsfile, you can write HTML code and use EJS template syntax:html<!DOCTYPE html> <html> <head> <title><%= title %></title> </head> <body> <h1><%= message %></h1> </body> </html> -
Render EJS templates in controllers: Next, in your controllers, you can use the
@Renderdecorator or theres.rendermethod to render EJS templates and send responses.typescriptimport { Controller, Get, Render } from '@nestjs/common'; @Controller() export class AppController { @Get() @Render('index') // Points to the index.ejs file in the views folder. root() { return { title: 'Hello World', message: 'Welcome to NestJS with EJS!' }; } }
These steps provide a basic guide on integrating the EJS template engine into a NestJS application. It's important to note that this integration is typically used for server-side rendering (SSR), which is becoming less common in modern web development due to frontend frameworks like React, Angular, and Vue handling the view layer. If your NestJS application needs to work with these frontend frameworks, you might prefer to build a pure API service rather than using EJS to render HTML.