Configuring a middleware with Vue Router

A middleware is an old and powerful concept that we have in software development, it is really useful when we have routing related patterns in our applications.

If you’re not sure about the meaning of middleware, there is a Simple Explanation of Express Middleware that can help you to learn more about how them work (at least in Express and Node, but the concept is the same).

But, is this only for backend? No, actually is very common in both (frontend or backend) when you have routing in your application, and we are using this concept since Single Page Applications appeared in our lives.

And… do my SPA website need this?
There are some examples that can explain when you can use a middleware:

  • Don’t allow users that didn’t logged into your website to visit a page.
  • Allow only certain types of users to see a page (Roles: Administrator, Editor, etc.)
  • Analytics.
  • Reset settings or clean storage.
  • Only allow to access to a page logged users older than a certain age.

And some others…

I really need this! How can I use with Vue?

Thanks to Vue Router this is going to be super easy! Because this plugin has implemented a similar concept called ‘Navigation Guards’.

Image of the docs about guards

Navigation Guards are really great, and let us to call a function before enter into a route, before it updates and before leaves

Example of guards

…or you can use global guards.

Example of global guards

But sometimes we need more than one middleware for the same route, we can solve the problem with Vue Router Multiguard package. That allow us to set an array of guards, like here.

Example using multiguard

At this point you can start to see that, to move from this to have real middlewares is going to be easy, let’s see a simplified example:

First, we define a mock user, imagine that you have a service, global state or something that returns to you the current user.

Object user with some data

Now, we can create our “real” example with middlewares:

Was really simple, all the pieces were there and we have only to join them 🤙

And you? How do you use middlewares with Vue?

Bonus: Vue Router has also In Component Guards that are really nice to get data before enter into a page.

Bonus2: If you read the docs you will discover that you can pass the next route to next() function, for example to redirect to login next(‘/login’)

Breaking projects at @PlainConcepts during day. Dreaming at @HelpDev_ , streaming at @JavascriptIO and learning at @NeedU_org over the night • Web GDE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store