nuxt-auth is experiencing difficulties retrieving token information through the refresh provider

I'm currently facing challenges with the login functionality in Nuxt 3.

To handle user authentication, I've installed the package @sidebase/nuxt-auth. Below are my configurations set in the file nuxt.config.ts:

auth: {
    globalAppMiddleware: true,
    baseURL: backendUrl,
    provider: {
      type: "refresh",
      endpoints: {
        signIn: { path: "/login/", method: "post" },
        signOut: { path: "/logout/", method: "get" },
        signUp: { path: "/register/", method: "post" },
        refresh: { path: "/refresh/", method: "post" },
        getSession: false,
      },
      pages: {
        login: "/login",
        register: "/register",
      },
      token: {
        signInResponseTokenPointer: "/access",
      },
      refreshToken: { signInResponseRefreshTokenPointer: "/refresh" },
    },

    enableSessionRefreshPeriodically: 5000,
    enableSessionRefreshOnWindowFocus: true,
    globalMiddlewareOptions: {
      allow404WithoutAuth: true,
      addDefaultCallbackUrl: "/",
    },
  },

The code snippet to retrieve the token from my server is located in file: server/api/auth/token.get.ts

import { getToken } from "#auth";
export default eventHandler(async (event) => {
  const token = await getToken({ event, cookieName: "auth" });
  console.log(token);
  return token || "no token present";
});

This is how I display the token on a page:

<script setup lang="ts">
definePageMeta({
    auth : false,
})
const headers = useRequestHeaders(['cookie'])
const {data : token} = await useFetch('/api/auth/token', {headers});
</script>
<template>
    <pre>
        {{ token }}
    </pre>
</template>

My approach for user login logic:

definePageMeta({
  layout: "front",
  auth: {
    unauthenticatedOnly: true,
    navigateAuthenticatedTo: '/token',
  }
});

const loginWithCredentials = async () => {
    try {
      let res = await signIn(
        { ...formData },
        { callbackUrl: '/token' }
      )
      console.log(res);
    } catch (error) {
      console.log("error", error);
    } 
}

It's important to note that I am using a custom backend to provide JSON data with JWT token properties "access" and "refresh". When I send a POST request to the URL backEndUrl/login/ with correct user credentials, I receive a response like this:

JsonResponse

After decoding the access token on , I see the following result:

JWTResponse

However, when I use the getToken() function, it returns null instead of the payload data. Any insights on what might be causing this issue?

Answer №1

Avoid creating a fresh route at server/api/auth/ since it serves as the standard base path for the @sidebase/nuxt-auth endpoint. (Check reference here)

Consider using server/api/token.get.ts as an alternative approach.

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

Tips for integrating tooltips in a dynamic highcharts chart

This image shows the desired final output View Highcharts here and I am looking to merge the date and stock value in a single tooltip, how can this be achieved? highcharts ...

What is the method for displaying a cube map reflection on an object without revealing the cubemap in the backdrop?

Is it possible to display a cube map reflection on an object without showing the cubemap in the background? I am interested in achieving a reflection on a lever mechanism without the cubemap being visible in the background. Instead, I would like the backg ...

Guide to directing a user through an Ajax call to a particular Controller and action

Here is a custom JavaScript function that updates data when the Update button is clicked. function UpdateData() { var obj = { "testData": $("#hdn_EditdsVal").val(), "feature": $("#hdn_EditdsVal").val() }; $.ajax({ url: ...

Leverage the power of Angular's route resolve function

Can anyone assist me with a problem I'm facing? I am looking for a way to delay the display of a view until my data is loaded. After some research, I was thinking of using a resolve in the route, but I can't seem to figure out how to implement it ...

A guide to loading CSS and JavaScript files asynchronously

Is it possible to use loadCSS (https://github.com/filamentgroup/loadCSS/blob/master/README.md) to allow the browser to asynchronously load CSS and JavaScript? This is what I currently have in my head tag: <link rel="preload" href="http://zoidstudios. ...

Is Next.js Dynamic Routing Failing You?

Recently, I attempted to implement Dynamic routing for a recipe app but encountered an issue where the page was not found. This problem has left me puzzled as I am fairly inexperienced with TypeScript, although not with React. // pages/recipes/[recipeId].t ...

Looking to bring in a non-ES6 library into VueJS without using export statements

Currently, I am faced with an interesting challenge. For a forthcoming VueJS project, we must utilize a library that is quite outdated but there is simply not enough time to redevelop it. The library is essentially a JavaScript file which consists of num ...

Are the Bootstrap columns arranged in a vertical stack instead of side by side?

I currently have two large columns that are stacked vertically on top of one another. I want them to be side by side, like | 1 | 2 |, so that the user can view both columns simultaneously. I am seeking tips or suggestions on how to resolve this issue. Whil ...

Is it possible to generate multiple modal windows with similar designs but varying content?

I am facing a challenge with 140 link items that are supposed to trigger a modal window displaying a user profile for each link. The issue is that each user profile contains unique elements such as three images, a profile picture, text paragraph, and socia ...

Issue: Proper handling of data serialization from getStaticProps in Next.js

I've been working on Next.js and encountered an issue while trying to access data. Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `nul ...

Transform the date to match the user's preferred timezone abbreviation

I am currently utilizing the momentJS library for timezone conversion logic within my JavaScript code. I retrieve the User Preference Timezone abbreviation from a web service response, but when attempting to convert the date using the Timezone abbreviation ...

Struggling to make image uploading function with Flask and JQuery

Utilize the code snippet below to submit forms and retrieve a modified version of text from Flask using AJAX and JQuery: from flask import Flask, render_template, request, jsonify app = Flask(__name__) @app.route('/') def index(): return re ...

What causes Vue to only update once when there are two closely timed mutations to reactive data?

Can you take a look at this simple example? export default { data() { return { name: "Amy", age: 18, }; }, computed: { combinedDataForWatching() { return { name: this.name, age: this.age, ...

React - Received an unexpected string containing a template expression with no curly braces present in the string

Currently, I am enrolled in a React tutorial online. I have inputted the code exactly as it was shown on the screen. Strangely, it seems to be working perfectly fine in the video but not when I try it myself. Below is the code snippet: <Link to={&apos ...

Content in tab remains stagnant

I am having trouble creating different tabs on a page with unique content in each tab's body. Whenever I click on a new tab, the body content remains the same. I'm not sure if it's an issue with how the tabs are set up in the HTML or if ther ...

Issues arising while passing a parameter to a Node.js module

I've been struggling with passing a variable to a module. In my node.js setup, I have the following structure: The main node.js server (server.js): // modules ================================================= var express = require('expr ...

Saving the selections from two drop-down menus into a single variable

I have a requirement to store the user selected values from two dropdown menus. These dropdowns are created using the selectize library in HTML: <div style="max-width: 200px"> <select id="dropdown-1" ...

Tips for reversing a sketch: Creating a timer where the text continuously refreshes causing it to intersect

Currently, I am working on developing a stopwatch that is functional. However, I am facing an issue where the text overlaps itself when it changes due to repetitive drawing. Removing the strokeText and fillText from the interval prevents it from changing a ...

Issue: Invalid element type - Error message displayed when attempting to show the Edit button

I am currently learning about React and trying to implement an edit button next to the rows for editing data in the database. However, I keep encountering this specific error message: Error: Element type is invalid: expected a string (for built-in compone ...

Tips for using ng-repeat in AngularJs to filter (key, value) pairs

I am trying to achieve the following: <div ng-controller="TestCtrl"> <div ng-repeat="(k,v) in items | filter:hasSecurityId"> {{k}} {{v.pos}} </div> </div> Code snippet for AngularJs: function TestCtrl($scope) { ...