How to serve static images in NestJS

2 min read 06-10-2024
How to serve static images in NestJS


Serving Static Images in NestJS: A Beginner's Guide

Problem: You're building a NestJS application and need to serve static images, like logos, banners, or product photos. You're unsure how to configure NestJS to handle image requests efficiently.

Solution: This article will guide you through the simple process of serving static images in your NestJS application. We'll cover the essential setup and provide practical examples to ensure you can easily display your images within your application.

Scenario: Imagine you're creating a website that displays product images. You've already designed the front-end and have your images stored in a dedicated public folder. Now, you need to make sure these images can be accessed and displayed correctly when users visit your website.

Original Code:

// app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Analysis:

The current code snippet lacks the necessary configuration to serve static files, including images. We need to add a middleware or static file handler to our NestJS application.

Solution:

NestJS offers a built-in solution for serving static files: the serveStatic middleware. Here's how you can implement it:

  1. Install the necessary packages:

    npm install @nestjs/platform-express serve-static
    
  2. Configure the middleware:

    // app.module.ts
    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { ServeStaticModule } from '@nestjs/platform-express';
    import { join } from 'path';
    
    @Module({
      imports: [
        ServeStaticModule.forRoot({
          rootPath: join(__dirname, '..', 'public'),
        }),
      ],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}
    

Explanation:

  • ServeStaticModule.forRoot configures the serveStatic middleware.
  • rootPath defines the directory containing your static files (images in this case).
  • join(__dirname, '..', 'public') ensures that the correct path to the public folder is specified.

Example:

Assume your images are stored in the public/images directory:

<!-- Your HTML file -->
<img src="/images/product1.jpg" alt="Product 1">

When the browser requests /images/product1.jpg, the configured serveStatic middleware will automatically serve the image from the public/images directory.

Additional Considerations:

  • You can customize the root path and other options for the serveStatic middleware. See the NestJS documentation for more details: https://docs.nestjs.com/techniques/static-assets.
  • For larger applications, consider using a dedicated CDN to serve static files for improved performance and security.

Benefits:

  • Simplified setup: Using the serveStatic middleware makes serving static files in NestJS a straightforward task.
  • Efficiency: Static files are handled directly by the server, reducing processing time and enhancing application speed.
  • Flexibility: The serveStatic middleware allows you to configure the root path and other options based on your project needs.

Conclusion:

Serving static images in your NestJS application is essential for displaying visual content. By utilizing the serveStatic middleware, you can easily configure your application to handle image requests efficiently, ensuring your website displays images correctly. Remember to tailor your configuration according to your project's specific requirements for optimal performance and flexibility.