Serve static

Making the upload folder directly accessible.

In order for the frontend to access the images, the upload folder needs to be readily accessible. No route will be used to access the files, but simply the path to them, like in a file system. This can be achieved by serving static content inside the upload folder.

First, we should install the following package from Nest.

yarn add @nestjs/serve-static

Then, let's create a module just to encapsulate the configuration of the ServeStaticModule.

nest g mo static

Now here, we may configure it. Note the resolve() in order to get an absolute path.

ServeStaticModule.forRoot({
  rootPath: resolve(BASE_PATH),
  serveRoot: '/files',
}),

The rootPath option defines that everything inside the upload folder will be publicly accessible, simply by traversing its contents, like in a file explorer. The serveRoot option defines how the rootPath will be accessed. In this case, it will be through the /files path.

We may then see an image if we access, for instance:

localhost:3000/files/products/1/images/photo.jpg

Commit - Serve static to access images

With this, the main content of this module is concluded. We'll now see further improvements.

Last updated