Problem store on middleware

How to fix this issue in middleware?
[nitro] [unhandledRejection] [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.
[nitro] [unhandledRejection] [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.
This is my middleware.
import { callOnce } from "#app";
import { serviceStore } from "~/stores/service";
import useService from "~/composables/use-service";

export default defineNuxtRouteMiddleware(async (to, from) => {
// Ensure this code runs only once
await callOnce(async () => {
const service = serviceStore(); // Pinia store
const { setHealthCheck, getHealthCheck } = useService(); // Composable

// Check if health status is already cached in cookies
const cachedHealthStatus = getHealthCheck();
if (cachedHealthStatus !== null) {
// Set the status in the store from the cookie
service.status = cachedHealthStatus === "true";
return; // Skip API call if status is cached
}

try {
// Perform the health check API call
await service.getCheckHealthz();

// Save the status in cookies based on the API response
await setHealthCheck(service.status);
} catch (error) {
console.error("API Health Check Failed:", error);

// Mark the API as unhealthy and save in cookies
await setHealthCheck(false);

// Optionally throw an error to block the route if necessary
throw createError({
statusCode: 500,
statusMessage: "API is currently unavailable.",
});
}
});
});
import { callOnce } from "#app";
import { serviceStore } from "~/stores/service";
import useService from "~/composables/use-service";

export default defineNuxtRouteMiddleware(async (to, from) => {
// Ensure this code runs only once
await callOnce(async () => {
const service = serviceStore(); // Pinia store
const { setHealthCheck, getHealthCheck } = useService(); // Composable

// Check if health status is already cached in cookies
const cachedHealthStatus = getHealthCheck();
if (cachedHealthStatus !== null) {
// Set the status in the store from the cookie
service.status = cachedHealthStatus === "true";
return; // Skip API call if status is cached
}

try {
// Perform the health check API call
await service.getCheckHealthz();

// Save the status in cookies based on the API response
await setHealthCheck(service.status);
} catch (error) {
console.error("API Health Check Failed:", error);

// Mark the API as unhealthy and save in cookies
await setHealthCheck(false);

// Optionally throw an error to block the route if necessary
throw createError({
statusCode: 500,
statusMessage: "API is currently unavailable.",
});
}
});
});
2 Replies
kapa.ai
kapa.ai4d ago
Hi @Adnan Erlansyah. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- The error you're encountering is related to accessing Nuxt composables or Pinia stores outside of the proper context in your middleware. To fix this issue, you need to ensure that you're using these composables and stores within the correct Nuxt context. Here's how you can modify your middleware to resolve the problem: 1. Use useNuxtApp() to get access to the Nuxt context:
export default defineNuxtRouteMiddleware((to, from) => {
const nuxtApp = useNuxtApp();

return nuxtApp.runWithContext(async () => {
// Your middleware logic here
const service = serviceStore();
const { setHealthCheck, getHealthCheck } = useService();

// Rest of your code...
});
});
export default defineNuxtRouteMiddleware((to, from) => {
const nuxtApp = useNuxtApp();

return nuxtApp.runWithContext(async () => {
// Your middleware logic here
const service = serviceStore();
const { setHealthCheck, getHealthCheck } = useService();

// Rest of your code...
});
});
By wrapping your middleware logic inside nuxtApp.runWithContext(), you ensure that all composables and stores are called within the correct Nuxt context. 2. Remove the callOnce function, as it's not necessary in this case and might be contributing to the context issues. 3. Make sure you're using the latest version of Nuxt 3, as some of these issues have been addressed in recent updates. Here's the modified middleware code:
export default defineNuxtRouteMiddleware((to, from) => {
const nuxtApp = useNuxtApp();

return nuxtApp.runWithContext(async () => {
const service = serviceStore();
const { setHealthCheck, getHealthCheck } = useService();

const cachedHealthStatus = getHealthCheck();
if (cachedHealthStatus !== null) {
service.status = cachedHealthStatus === "true";
return;
}
try {
await service.getCheckHealthz();
await setHealthCheck(service.status);
} catch (error) {
console.error("API Health Check Failed:", error);
await setHealthCheck(false);
throw createError({
statusCode: 500,
statusMessage: "API is currently unavailable.",
});
}
});
});
export default defineNuxtRouteMiddleware((to, from) => {
const nuxtApp = useNuxtApp();

return nuxtApp.runWithContext(async () => {
const service = serviceStore();
const { setHealthCheck, getHealthCheck } = useService();

const cachedHealthStatus = getHealthCheck();
if (cachedHealthStatus !== null) {
service.status = cachedHealthStatus === "true";
return;
}
try {
await service.getCheckHealthz();
await setHealthCheck(service.status);
} catch (error) {
console.error("API Health Check Failed:", error);
await setHealthCheck(false);
throw createError({
statusCode: 500,
statusMessage: "API is currently unavailable.",
});
}
});
});
This modification should resolve the "Nuxt instance unavailable" error you're experiencing. The runWithContext method ensures that the Nuxt context is correctly applied to your middleware logic, allowing you to use composables and Pinia stores without issues. For more information on this topic, you can refer to the Nuxt 3 documentation on runWithContext. If you continue to experience issues, make sure that your useService composable and serviceStore are properly defined and exported from their respective files. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4d ago
<@1079709612078534676> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?