```html

Flash Messages

This library provides functionality for displaying **one-time messages (flash messages)** to users in web applications. Flash messages are useful for providing feedback to users, such as success or failure notifications after form submissions, or validation errors.

Flash messages can be used in two ways:

Using the @Flash() Decorator

Use the @Flash() decorator to inject a NestMvcFlash instance and set flash messages.

@Post()
async create(@Body() dto: any, @Flash() flash: NestMvcFlash, @Res() res: Response) {
  if (!dto) {
    // MVC exception handling: Displays a 'failure' message while keeping the data entered in the form on the screen.
    throw new MvcValidationException('Operation failed');
  }
  // Sets the success message.
  flash.success('Operation successful');
  return res.redirect('/admin/documents');
}
 

Using the @Req Decorator and NestMvcReq Object Type

NestMvcReq is an extended request object that adds view and flash properties to the existing Request object. This allows you to use flash functionality with req.flash.

@Post()
async create(@Req() req: NestMvcReq, @Res() res: Response) {
  if (!req.body) {
    // MVC exception handling: Displays a 'failure' message while keeping the data entered in the form on the screen.
    throw new MvcValidationException('Operation failed');
  }
  // Sets the success message.
  req.flash.success('Operation successful');
  return res.redirect('/admin/documents');
}
 

Important: Session Dependency

Flash messages internally rely on sessions. While rendering will not fail if sessions are not enabled, a persistent warning message will occur. Therefore, for reliable use of flash messages, sessions must be enabled. We recommend installing express-session to use these features.

npm install express-session
 

main.ts configuration:

import * as session from "express-session";

app.use(
  session({
    secret: process.env.SESSION_SECRET || "your-secret-key"
  })
);
```