Using Vision’s global contexts for auth data

A simple way to identify if your user is logged in.

Using Vision’s global contexts for auth data

I seem to be on a hapi theme right now. It’s new to me and seems a bit less well covered than Express in Google results, so I figure I might as well write stuff down and hope it helps someone else.

The problem

I was trying to do the usual thing for the navbar, only showing the register/login/register buttons when it makes sense. But how to know which to display? I don’t want to add loggedIn to the context for every h.view() call, that’s just ugly.

The solution I found

When setting up the server views, you can supply a context to Vision:

The global context option can be either an object or a function that takes the request … The contents of the context will be merged with anything else you supply to a page being rendered.

So - building on that:

function buildVisionContext(request) {
  return {
    loggedIn: request.auth.isAuthenticated
  };
}

async function registerVision(server) {
  let cached;

  if (!process.env.NODE_ENV || process.env.NODE_ENV === "development") {
    cached = false;
  } else {
    cached = true;
  }
  server.log(["debug"], `Caching templates: ${cached}`);
  server.views({
    engines: { ejs: require("ejs")},
    relativeTo: __dirname + "/../",
    path: 'templates',
    isCached: cached,
    context: buildVisionContext
  });
}

And now, every page rendered with h.view() will automatically have that variable available to it.


Photo by Markus Spiske on Unsplash

Subscribe to Paul Walker

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe