Introduction to Nuxt Middleware
And the most important thing in Nuxt is middleware. So you can see we have a directory called middleware and a simple readme file which says that middleware lets you define custom functions that can be run before rendering either a page or a group of pages. This is very important: before rendering. That means this middleware will work before anything acts on your pages.
So how we can create a simple middleware and how we can apply it to this Nuxt functionality? This video is all about that. So let's create a simple file, and a file is just a name like test.js. So this is just a simple javascript file and inside that we just need to say export default and we are exporting a function, and whatever we will do in this function is the middleware. That's very easy.
So I am just logging something. So I will say, "I am middleware." So I'm just logging this: "I am middleware". So let's just fix this linting and like this.
Configuring ESLint for Console Logs
And yeah, it says unexpected console statement. I told you we need to give the comment, but now this time I'm going to fix it properly. So I will go to .eslintrc.js file. At the last, we have rules and here I will say no-console and make it off. And when I save this, now I will start the server. And if you have already started the server, you need to restart it to have this effective. Okay, so this is going to be changed. And it's again saying something, no problem. It's done.
Applying Middleware to a Single Page
And how we can apply this middleware to any page? It's very easy. Again, go to any page, and remember these middleware only affect the pages. So whatever pages you have inside the pages directory will going to have the benefit of middleware. So I will go to the about.vue file.
And just like we have a head function, just like we have asyncData, and now we have a new thing which is called middleware. And we just need to define the middleware. So middleware name is test. So whatever the file you have created inside the middleware, that will become your middleware name. So the test.js file will become the middleware name of test. And let's just give a comma here, save this file, and whenever we visit about, we are assuming that there is a log of "I am middleware".
And that works. So let's just go here and I will open the console or dev inspection. Clear the console. As soon as I will go to About, you can see here we have "I am middleware." That means it is applied. And to show you that this middleware is going to work before rendering the page, I will just refresh this page. So if I refresh this page, hmm, we can't see "I am middleware" here because whenever we are refreshing, this page is rendering on the server side. That means our log is on the server side. So to check that log, we need to go here and now we can see here on the terminal, we can see we have "I am middleware," and that's coming from the server. And this is very, very important thing.
Applying Middleware Globally
But this is only for About. What if you want to apply this middleware to every page inside your pages directory? Suppose you have 100 or 50 pages, do you need to go to every page and write it? No, there is a simple feature or simple functionality you need to apply. Just go to nuxt.config.js file. It's exporting all the configuration related to your Nuxt, like you have router. Anywhere you can say router is have middleware and the middleware name is test. And I just give a comma.
And because we have made change in the Nuxt config file, we need to kill the server and restart it. So this time we are expecting a console log on every page, even on the server side of every page. So yes, it is working and as soon as this is completed, you can see two console logs. Why? Because it is hot reloading and whenever the server is started, it's reloaded. So what I'm going to do, I will clear it and now I will show you this thing. So if I go to home, "I am middleware" is there. If I go to about, we get two "I am middleware." Why? Because one is globally we have applied here, and one is on this about page. So let's just delete this and save this file. It is recompiled. And this time I am refreshing. So I refresh on about, still I get "I am middleware."
So the next point is how we can use this middleware in a real way? It's just a console.log and nothing is happening here.
A Practical Use Case: Auth Check with Axios
So for that, to show you how this is actually going to work, I'm going to this website which is called reqres.in or requestresponse.in, reqres.in. This is giving you a simple API to work or to test. So if you go here and you can see login successful whenever you give API/login with these credentials, it will give you the token, and the same token this one. So let's just copy this from here and I will use Axios for this.
You know we already have Axios which is like @nuxtjs/axios, but this Nuxt-Axios is not going to work normally like axios.post. There is a simple catch, and the catch is you need to prefix a dollar sign with everything, like $axios.$post, $get, $delete, these kind of things. So we need to give a Post request to this route plus api/login like this and we need to give data which is this one. So copy and paste it.
Yeah, we have these things and let's just do the .then part. So we will get the response and whenever we get the response, we will say log out response. Okay, so yes this is there but now it says, "Oh $axios, I don't know what you are talking about." So every middleware will get the context. Context is like your Nuxt, everything on the Nuxt.
So to show you what context means, I will log the context and just comment this. So I log the context. I will go here, and I think it's on the server side. Yeah here we have the context, and we have all the list of things we require for the Nuxt. So you don't have to care about all these things, but what you need to care about is this context already has Axios. So you need to say context.axios and this time it's going to work properly. This means, yeah, we have this token here because it's already reloaded whenever I save this file.
Implementing Conditional Redirection
So, we have this token here, and now we can simply use this token to do some crazy thing. Like what I'm going to do, I will say here, like if (response.token !== this_token) then redirect to base URL or home page. But again, this redirect came from context. So, context.redirect. And let's just see. We have here, and yeah, because it is the same token we have, so it's working.
So if I remove all these things and the token is now going to mismatch, it's now redirecting... it has to redirect to the homepage but it's not doing this. Let's see why, because it's saying something. And it is saying that Cannot set headers after they are sent to the client. So what I need to do, I will just return it, and this time if I go refresh this page, yeah, you can see I am redirected to the homepage. And if I go to about once more... actually, there is some problem. The problem is this middleware is applied to everywhere, to the base URL also. So we can go to about, but it will redirect to the base URL. We can go to Inspire, it will redirect to the base URL.
So let's just remove this from our Nuxt config and obviously we need to restart the server. It is recompiled. Go here on the about page and let's refresh this and go to about. Yeah, we are on the about page but this middleware is not applied anywhere. So once again, let's apply it on the about page.
Refining the Code and Destructuring Context
So now, whenever we visit the about page, it will call this API, and if it is not going to match with the token, then it will redirect to the base URL. Okay. So let's go here and try to go to About. No, we can't. Then if I go on the URL and type /about, yeah, we are redirected back to the base URL.
And this is how your middleware is going to work properly with any kind of page and everywhere. So this is very nice. You need to be clear about that. But one thing more, you can see we are using context two times. So instead of this, I will delete this context and I will just say inside curly braces, I want axios and I want redirect. So both are here and this time it's also going to work properly. Yeah, you can see. So how the middleware is going to work and you can apply, and we will actually be going to see how we will use this middleware in a real kind of application.
So we will meet in the next episode. Till then, goodbye.