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:
After decoding the access token on , I see the following result:
However, when I use the getToken() function, it returns null instead of the payload data. Any insights on what might be causing this issue?