Alexander Doloz Alexander Doloz - 1 year ago 92
Swift Question

How to serve static files using Vapor?

I'm trying to write server side application using Swift and Vapor framework. However, I can't figure out, how to serve static files using Vapor. It's not enough to just move them to the


How can I do that?

I performed steps which Tanner Nelson suggested but it still doesn't work.

What I tried so far:

  1. vapor build
    vapor run
    (using Vapor Toolbox v0.6.1).

  2. ./build/debug/App
    from root directory (which contains

  3. Run in Xcode 8 beta after editing scheme as Tanner Nelson suggested.

In all this cases I get error
{"error":true,"message":"Page not found"}

I have file
inside a
folder and also the same file inside
folder. I try to request it and it fails. Requests that I made:
. However, other routes work fine.

UPD 2. Well, that was all my mistakes. First, file that I think was called
, actually was called
. Second, case matters when you make a request. I also tried to request file with name
but write file extension as
, so got an error.

So, just to recap: if you experience the same problem as me, follow the Tanner Nelson's answer and make sure that name of requested file exactly matches name of file on disk.

Answer Source

Vapor folder structure from Docs:

├── App
│   └── main.swift
│   └── ...
├── Public
├── Resources
└── Package.swift

Any files in the Public folder will be served by default if no routes have been registered that conflict with the file name.

For example, if you have a file Public/foo.png and the following main.swift file:

import Vapor

let drop = Droplet()

drop.get("welcome") { request in
    return "Hello, world"


A request to localhost/welcome would return "Hello, world" and a request to localhost/foo.png would return foo.png.

If this is not working properly, it's likely that your working directory is not configured properly. This can happen if you are running your project from Xcode or you are running it from the command line from a folder that is not the root directory of the project.

To fix Xcode, go to Schemes > App > Edit Scheme > Run > Options > Working Directory > [x] Use Custom Working Directory and make sure the directory is set to the root of your project (where the Package.swift resides).

Xcode working directory

To fix when running from the command line, make sure you are running the application from the root directory. i.e., the run command should look something like .build/debug/App since the .build folder is located in the root directory.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download