When you’re creating a Vapor app, you might at some stage want to load some resources that you process in your code, e.g., some static data in JSON format that you want to augment.

I couldn’t find documentation for it and getting it to work required me to do a detour past the helpful folks in the Vapor discord group, so here’s a quick how to. Note, that this is for Vapor 4.

You should put the files into a folder at the root of your Vapor app, e.g., into Resources. Don’t put them into the your Sources folder.

In your code, when you configure your Application instance, you can get the path and trigger loading of the data. You could for example add the following to your Sources/App/configure.app:

public func configure(_ app: Application) throws {
  // Existing set-up code
  let path = app.directory.workingDirectory + "Resources/"
  StaticDataManager.shared.load(directory: path)

This should then work when running Vapor from the command line.

You’ll need to do more setup when running using Docker or Xcode:

  • Docker: In your Dockerfile add a line like COPY --from=build /build/Resources /run/Resources, this makes sure the resources will be copied across when packaging up your app.
  • Xcode: Edit your Scheme, and under “Run” tick the box next to “Working Directory” and then select the root path of your Vapor app. This prevents Xcode from running from it’s usual location somewhere in caches or derived data, which wouldn’t have included those resources. (Kudos to Vapor’s own tanner0101 on Stack Overflow.)