Middleware Tutorial for Server-Side Swift Using Vapor 4: Getting Started

In this tutorial, you’ll learn how to create middleware — a module that sits between an app and the browser and removes some of the work load from your web app. By Walter Tyree.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Logging Responses

Thus far, the middleware has been acting on a request object. However, it can also interact with a response object as it leaves the server and returns to the browser. This next middleware will only log redirected responses. You’ll tag the log entries to make it easier for someone to extract them later and do further analysis.

Open Sources/App/Middleware/Logging.swift. As with the API file, it only has the one required protocol method:

func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {

It’ll be called as part of the request chain. Notice that the method also has a Responderproperty called next. That property is an EventLoopFuture because the response hasn’t happened yet. When you write code for the future property, it won’t execute until the response object exists. Update the return line and log things in the future:

  // 1
  return next.respond(to: request).map { res in
  // 2
    if res.status == .movedPermanently {
    // 3
      request.logger.info("[REDIRECT] \(request.url.path) -> \(res.headers[.location])")
    }
    return res
  }

Here’s what the logger does now:

  1. Adds .map to the standard return next.respond(to:) to let you access the future response as res.
  2. Uses an if statement so you’ll only log responses that were redirects.
  3. Writes a message to the standard logger object at the .info level.

The last step is to enable your new logging middleware. Open configure.swift and replace TODO:// Add middleware with app.middleware.use(Logging()). Run the app again. Notice that when you request one of the short links you added earlier, there will be a new log statement.

Note: Many browsers cache redirect requests by default. If your browser does this, a log statement won’t be executed because the browser is performing the redirect and bypassing the server. To prevent this, you can use Incognito mode, or clear your browser’s cache after enabling logging.

Where to Go From Here?

Download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.

In this tutorial, you learned about middleware, including how to add an API key to protect some of the routes of your web app, and how to add specially formatted entries to the server logs.

If you want to do more with your project, consider:

  • Using Redis or some other data store to have many different API keys.
  • Enhancing the logging to make it easy for API keyholders to report on how their short links are being used.

If you’re interested in learning more, the Vapor Docs contain more information and resources on middleware.

We hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!