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

AngularJS redirection to a different state by utilizing a URL

When I need to direct a user to a specific state, typically I would use the following code: $state.go('state_name'); $state.transitionTo('state_name'); This method usually takes users to /state_name. However, there is one particular s ...

Creating visual content on Canvas using JavaScript

Having an issue with stacking multiple images on separate Canvas layers, and they're not drawing on the canvas. Can anyone help me figure out what I'm missing? Thanks CSS .positionCanvas{ position: absolute; left:0; righ ...

Having difficulty adding items to the shopping cart

While working on a simple checkout system using django and react, I encountered an issue. Upon clicking the add to cart button, instead of adding the item to the cart as intended, I receive a 404 page not found error. I suspect that the problem may lie in ...

How to dynamically alter a PHP variable using a JavaScript button click on the existing webpage

I've spent the last hour scouring stackoverflow for answers to my problem, but trying out solutions has only resulted in errors - perhaps because I'm attempting to implement it on the same page. I've experimented with saving the value to a ...

Tips for accessing the initial value within JSON curly braces

In my code, there is a function that returns the following: { 'random_string': '' } The value of random_string is an unknown id until it is returned. How can I extract this value in JavaScript? Appreciate any help. Thanks. ...

Creating distinct short identifiers across various servers

Utilizing the shortid package for creating unique room IDs has proven effective when used on a single server. However, concerns arise regarding the uniqueness of IDs generated when utilized across multiple servers. Is there a method to ensure unique ID g ...

Tips for incorporating MUI into your Redwood JS project

Trying to integrate MUI into Redwood JS has been a challenge for me. I attempted to run the following command in the project directory: yarn add @mui/material Unfortunately, an error message appeared in the console stating: An error Running this command w ...

Managing a JSON request from an AJAX form using PHP - the ultimate guide!

I'm encountering some issues with my PHP handler. Here is the code snippet for my handler: <?php // Creating headers $headers = array( 'accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8&a ...

Accessing props in setup function in Vue 3

I am encountering issues when trying to access the props value (an array) in my composition API setup. The component I have is called DropDown, and I am passing it an array of objects. Here's what I need to achieve: export default { emits: ['up ...

Enhance your AJAX calls with jQuery by confidently specifying the data type of successful responses using TypeScript

In our development process, we implement TypeScript for type hinting in our JavaScript code. Type hinting is utilized for Ajax calls as well to define the response data format within the success callback. This exemplifies how it could be structured: inter ...

I am attempting to build a party planning website but I am encountering an issue where the output is not generating properly. Whenever I click on the submit button, the information I input

I am struggling to create a party planner website and encountering issues with the output. Whenever I click on the submit button, the form just clears out without any feedback or result. Here is what the expected output should be: Validate event date 1: ...

res.render() Displaying Data in Frontend using Local Variables

I have a question regarding defining local variables in Express. When I use res.render(view, {variable: variable}), how can these variables be accessed on the frontend? Where are they stored? I attempted to access a variable with console.log(variable), but ...

Calls to debounced functions are postponed, with all of them running once the waiting timer is complete

Utilizing the debounce function to create a real-time search feature. Researching more on debouncing from https://css-tricks.com/debouncing-throttling-explained-examples/, it seems like the function should control the number of calls made. In my scenario ...

Issue with large date changes causing MUI DatePicker to freeze

The MUI DatePicker, whether from Labs or X, was functioning perfectly. However, I am now facing an issue where it hangs when trying to change the date by ten years. It appears that the code gets stuck in an endless loop, yet there are no errors displayed i ...

Unable to retrieve data from Meteor find query

I have a collection created in collections.js portfolioItems = new Mongo.Collection('portfolioitems'); This collection is then subscribed to in subscriptions.js Meteor.subscribe('portfolioitems'); And published in publications.js M ...

What is the best way to extract a JSON object from a website search using getJSON or similar techniques?

Can anyone provide guidance on utilizing .getJSON() to access JSON-encoded information from a website that is being searched? I've implemented a Google Custom Search API for my site with the aim of retrieving the JSON file from the search results. Fo ...

Enhancing Security: Implementing Node.js API Authentication

Looking for guidance on setting up multiple authentications with different roles in Next.js development. Can anyone help me navigate this aspect of website building? Using Next.js for the frontend Utilizing Node.js and JWT (JSON web token) for the backend ...

AngularJS: The image loader will display on the initial div

I am trying to implement a loader that will hide after a certain amount of time when the user clicks on a profile. I have used a timeout function to achieve this behavior. However, the loader is appearing on the left side instead of within the respective ...

Vue.nextTick incorrect detection

scenario: const Constructor = Vue.extend(MyComponent); function createComponent() { vm = new Constructor({ props, }).$mount(); return vm; } Query: In my testing process, I notice vm.$nextTick().then(() => { expect(result).to.eq ...

"Relating to meteorjs, admin users are akin to those in

Looking for a package or tutorial to create admin users similar to Django. I want to be able to create superusers through the terminal and have the ability to personalize user schemas with Collection2. Additionally, I would like to remove the option for ...