N
Nuxt7mo ago
Biscuit

A composable that requires access to the Nuxt instance was called outside of a plugin,

I have two middlewares. control-access is going to redirect the user to home if there's a valid jwt token. auth is going to redirect the user to /login if the token is not valid and I can't retrieve a new one. I am storing the accessToken using a cookie useCookie('token'). This is handled by a composable called useAccessToken. So basically the pages call the middlewares that call this composable. I am getting the following error
[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at `https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables`.

at Module.useRequestEvent (\nuxt\dist\app\composables\ssr.js:7:58)
at readRawCookies (\node_modules\nuxt\dist\app\composables\cookie.js:123:101)
at Module.useCookie (node_modules\nuxt\dist\app\composables\cookie.js:28:19)
at refreshAccessToken (\composables\useAccessToken.ts:32:29)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async verifyAccessToken (\composables\useAccessToken.ts:47:7)
at async \middleware\controlAccess.ts:14:86
at async Object.callAsync (node_modules/unctx/dist/index.mjs:72:16)
at async node_modules\nuxt\dist\pages\runtime\plugins\router.js:161:26
[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at `https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables`.

at Module.useRequestEvent (\nuxt\dist\app\composables\ssr.js:7:58)
at readRawCookies (\node_modules\nuxt\dist\app\composables\cookie.js:123:101)
at Module.useCookie (node_modules\nuxt\dist\app\composables\cookie.js:28:19)
at refreshAccessToken (\composables\useAccessToken.ts:32:29)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async verifyAccessToken (\composables\useAccessToken.ts:47:7)
at async \middleware\controlAccess.ts:14:86
at async Object.callAsync (node_modules/unctx/dist/index.mjs:72:16)
at async node_modules\nuxt\dist\pages\runtime\plugins\router.js:161:26
here my files
export default defineNuxtRouteMiddleware(async (to, _from) => {
const config = useRuntimeConfig();
const { verifyAccessToken } = useAccessToken(config.public.appServer);

await verifyAccessToken();
const currentToken = useCookie("token");
if (currentToken.value) {
return navigateTo("/");
}
});
export default defineNuxtRouteMiddleware(async (to, _from) => {
const config = useRuntimeConfig();
const { verifyAccessToken } = useAccessToken(config.public.appServer);

await verifyAccessToken();
const currentToken = useCookie("token");
if (currentToken.value) {
return navigateTo("/");
}
});
1 Reply
Biscuit
BiscuitOP7mo ago
composable
export const useAccessToken = (baseUrl: string) => {
const authHeaders = () => {
return {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${useCookie("token").value}`,
} as HeadersInit,
};
};

const setAccessToken = (token: string | undefined | null) => {
if (!token) return;
useCookie("token").value = token;
};

const refreshAccessToken = async () => {
try {
const response = await fetch(`${baseUrl}/refresh-token`, {
headers: {
"Content-Type": "application/json",
},
credentials: "include",
});

// Check if the request was successful
if (!response.ok) {
throw new Error("Refresh token failed");
}

// If successful, you can process the response here
const data = await response.json();
console.log({ refresh: data });
} catch (err) {
console.log({ err });
useCookie("token").value = null;
}
};

const verifyAccessToken = async () => {
try {
const response = await fetch(`${baseUrl}/me`, {
headers: authHeaders().headers,
});

// Check if the request was successful
if (!response.ok) {
throw new Error("Verify token failed");
}

// If successful, you can process the response here
const data = await response.json();
console.log({ refresh: data });
} catch (err) {
console.log({ err });
await refreshAccessToken();
}
};

return { authHeaders, setAccessToken, refreshAccessToken, verifyAccessToken };
};
export const useAccessToken = (baseUrl: string) => {
const authHeaders = () => {
return {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${useCookie("token").value}`,
} as HeadersInit,
};
};

const setAccessToken = (token: string | undefined | null) => {
if (!token) return;
useCookie("token").value = token;
};

const refreshAccessToken = async () => {
try {
const response = await fetch(`${baseUrl}/refresh-token`, {
headers: {
"Content-Type": "application/json",
},
credentials: "include",
});

// Check if the request was successful
if (!response.ok) {
throw new Error("Refresh token failed");
}

// If successful, you can process the response here
const data = await response.json();
console.log({ refresh: data });
} catch (err) {
console.log({ err });
useCookie("token").value = null;
}
};

const verifyAccessToken = async () => {
try {
const response = await fetch(`${baseUrl}/me`, {
headers: authHeaders().headers,
});

// Check if the request was successful
if (!response.ok) {
throw new Error("Verify token failed");
}

// If successful, you can process the response here
const data = await response.json();
console.log({ refresh: data });
} catch (err) {
console.log({ err });
await refreshAccessToken();
}
};

return { authHeaders, setAccessToken, refreshAccessToken, verifyAccessToken };
};
login page
<template>
<div class="grid xs:grid-cols-2 h-full">
<div class="hidden xs:flex w-full bg-primary-800" />
<custom-card
title="login"
:img="{ src: 'logo.png', height: 100, width: 100, alt: 'gighub' }"
>
<template #content>
c
</template>
</custom-card>
</div>
</template>

<script setup lang="ts">
definePageMeta({
middleware: "control-access",
layout: "auth",
});
<template>
<div class="grid xs:grid-cols-2 h-full">
<div class="hidden xs:flex w-full bg-primary-800" />
<custom-card
title="login"
:img="{ src: 'logo.png', height: 100, width: 100, alt: 'gighub' }"
>
<template #content>
c
</template>
</custom-card>
</div>
</template>

<script setup lang="ts">
definePageMeta({
middleware: "control-access",
layout: "auth",
});
Want results from more Discord servers?
Add your server