How can you limit access to certain routes in Nuxt.js to only clients who possess a valid JWT token?

In Nuxt.js, implementing authentication can be done in the following steps:

  1. The client authenticates by sending its credentials in an HTTP request to a specific API route in the Nuxt backend;
  2. The Nuxt backend responds with a JWT token for accessing protected routes;
  3. When the authenticated user tries to access a protected route, they include their JWT token in the header of the HTTP request sent to the Nuxt backend;
  4. The backend validates the JWT token and provides the requested page JSON data to the client.

One question that arises is how to inform the Nuxt backend to check the JWT token for certain protected routes before serving the page JSON data. Essentially, the query is about where precisely in Nuxt this type of validation should be implemented?

Answer №1

Feeling a bit puzzled with your mention of API data and JSON pages, but the solution lies in creating middleware to protect your page.

Consider setting up a middleware called auth.js:

export default async function ({ store, $axios, redirect }) {
  let valid = await $axios.$post('/api/checktoken')
  if (!valid) {
    redirect('/')
  }
}

To secure your page, establish an API for token verification. Storing the token in a cookie can simplify this process as cookies are automatically included in HTTP requests.

Next, apply the auth middleware to a specific page:

<script>
export default {
   middleware: "auth"
}
</script>

If safeguarding backend routes is necessary, create another middleware:

  async authenticate(req, res, next) {
    let token = await cookieService.getTokenFromCookie(req)
    if (!token) return errorService.resError(res, 400, 'Authorization failed')
    let tokenValid = await tokenService.verifyToken(token)
    if (!tokenValid)
      return errorService.resError(res, 400, 'Authorization failed')
    let decodedData = tokenService.decode(token)
    if (!decodedData)
      return errorService.resError(res, 400, 'Authorization failed')
    res.locals.userId = decodedData.userId
    res.locals.role = decodedData.role
    next()
  }

This method involves extracting the token from a cookie, verifying its validity, and decoding it for access to its information. The data can then be stored in res.locals for subsequent middleware or endpoints.

Remember to call next() to proceed to the next middleware or endpoint:

function endpoint(req, res) {
   let { userId, role } = res.locals
   // Perform actions....
}

Apply the authentication middleware to relevant API endpoints:

app.use("/some/api/point", authenticate, endpoint)

By using authenticate in various API routes, you ensure consistent protection across different parts of your application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Selenium and Python to scrape text from a continuously refreshing webpage after each scroll

Currently, I am utilizing Selenium/python to automatically scroll down a social media platform and extract posts. At the moment, I am gathering all the text in one go after scrolling a set number of times (see code below), but my objective is to only gathe ...

What is the best way to generate an array of IDs from the chosen options in the Vue-Multiselect plugin?

I have successfully developed a Laravel Vue SPA application. At the moment, I am able to fetch data in object format and display the names using vue-multiselect () upon selection. Additionally, I can save the selected options to the database in an object f ...

Which specific files do I have to edit in order for Laravel to acknowledge a new data type?

Currently, I am honing my skills in Laravel by working on a Laravel Breeze application. One task that I have set for myself is to incorporate a postal code field into the existing User model, including the registration form. To tackle this challenge, I dec ...

Load information into a different entity

I need help with adding new values to an existing object. When I receive some form data from noteValue, I also have additional input data in my component under person that I would like to integrate into noteValue before saving it. let noteValue = form.va ...

Tips for removing a row without impacting the rest of the rows

I'm currently developing a VueJs parent component with the ability to generate rows dynamically. This component invokes another component responsible for populating two dropdowns using axios - one for categories and the other for subcategories (with t ...

Attempting to display a collection of 16 diverse images by utilizing the Math.random function in conjunction with a

I have been attempting to retrieve 16 random images, but I keep getting duplicates. I am aware that a modification needs to be made to the one => one.number filter, however all attempts so far have been unsuccessful. import React from "react"; import ...

How can I convert a string to an integer in Node.js/JavaScript in terms of cardinality?

Imagine a scenario where a user can input any string such as "1st", "2nd", "third", "fourth", "fifth", "9999th", etc. The goal is to assign an integer value to each of these strings: "1st" -> 0 "2nd" -> 1 "third" -> 2 "fourth" -> 3 "fifth" -&g ...

Unlocking the potential of resizable bootstrap table columns in React

Currently utilizing a bootstrap table <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th>#</th> <th>Table heading</th> </tr> < ...

Find all objects in an array of objects that contain at least one value that matches a given string

I am currently integrating search functionality in my application. The UI search results are generated from an array of objects. My goal is to loop through the name, custNumber, and sneak values in each object and display only the ones that contain a subst ...

What is the best way to manage DOM modifications in a responsive design layout?

Developing a responsive website with only one breakpoint can be challenging, especially when restructuring the DOM to accommodate different screen sizes. It's important to consider not just CSS and media queries, but also how the elements are arranged ...

The extended class possesses a distinct type from the base class, which is reinforced by an interface

Is it possible to write a method that is an extension of a base class, but with a different return type, if supported by the shared interface, without adding a type declaration in class 'a'? In practical terms, classes a & b exist in JavaScript ...

Dayjs is failing to retrieve the current system time

Hey everyone, I'm facing an issue with using Dayjs() and format to retrieve the current time in a specific format while running my Cypress tests. Despite using the correct code, I keep getting an old timestamp as the output: const presentDateTime = da ...

What is the best way to handle multiple JSON data using jQuery?

Understanding how to utilize jquery for parsing simple json is a valuable skill. json { "Symbol": "AAL.L", "Name": "ANGLO AMERICAN", "Last": "3061.50", "Date": "7/26/2011", "Time": "11:35am", "Change": "+3 ...

Why is it that styling <div> and <img> with a URL doesn't seem to work, even when applying the same styles?

In the example I have, I apply the same styling to an image and a div. Interestingly, the styling on the div makes the image look significantly better, while on the image itself it appears distorted. What could be causing this discrepancy? Both elements a ...

Unlocking the secrets of retrieving store values in Vue.js components

This is the code for my store.js file: import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { isLoggedIn: !!localStorage.getItem('token'), isLog : !!localSto ...

Setting up popover functionality in TypeScript with Bootstrap 4

Seeking assistance with initializing popovers using TypeScript. I am attempting to initialize each element with the data-toggle="popover" attribute found on the page using querySelectorAll(). Here is an example of what I have tried so far: export class P ...

Attempting to replicate the functionality of double buffering using JavaScript

In my HTML project, I have a complex element that resembles a calendar, with numerous nested divs. I need to refresh this view in the background whenever there are updates on the server. To achieve this, I set up an EventSource to check for data changes on ...

Storing property data outside of the render method in ReactJS is key for efficient

I have encountered an issue while attempting to map data outside of the render method in my function and return it within the render. The mapping error is causing confusion as I am uncertain about its underlying cause. Below is the function responsible fo ...

An odd issue has arisen where the website functions properly in Firefox 3.0 but encounters problems when accessed in Firefox 3

Could someone investigate this issue for me? When you click on the showcase and then on the logo, a modal window should open with the logo. It works perfectly in FF 3.0, but in FF 3.5, the tab switches from showcase to home after clicking the logo. Even ...

Leveraging Ajax in Django to communicate with the backend and showcase the outcome

I need assistance with implementing ajax functionality to send user input to a Django backend for text processing, and then display the results. However, due to my limited experience with ajax, I'm struggling to figure out where I'm going wrong. ...