Serving static files

One of the basic requirements of a web app is the ability to serve static files.Serving static files from a LoopBack application is very simple - just call theapp.static(urlPath, rootDir[, options]) method. The variables in the API areexplained below.

  • app: An instance of a LoopBack application.
  • urlPath: The path where the static assets are to be served from. Refer topath examples in theExpress docs for possible values.
  • rootDir: The directory where the static assets are located on the filesystem.
  • options: An optional object for configuring the underlyingexpress.staticmiddleware.Here is an example of configuring an app to serve the static assets from adirectory named public at /.

src/application.ts

import * as path from 'path';

export class TodoListApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    super(options);

    // ...

    this.static('/', path.join(__dirname, '../../public'));
  }
}

You can call app.static() multiple times to configure the app to serve staticassets from different drectories.

app.static('/files', path.join(__dirname, 'files'));
app.static('/downloads', path.join(__dirname, 'mp3s'));

You can also call app.static() multiple times on the same mount path to mergefiles from multiple filesystem directories and expose them on the same URL path.When a file with the same name is present in multiple directories mounted at thesame URL path, then the precedence is given the file from the directory that wasregistered earlier.

app.static('/files', path.join(__dirname, 'files'));
app.static('/files', path.join(__dirname, 'other-files'));

And app.static() can be called even after the app have started.

await app.boot();
await app.start();
app.static('/files', path.join(__dirname, 'files'));