patchamamma
patchamamma
NNuxt
Created by patchamamma on 10/11/2024 in #❓・help
Dynamic Subdomain Support in Nuxt3
I'm working on implementing dynamic subdomain handling in Nuxt by using a router.options file, as described in this article https://zernonia.keypress.blog/why-keypress. However, I'm facing an issue where the platform page doesn't render correctly when a user visits it through a subdomain, it shows the error 404 page not found: /. I rather don't want to use the nuxt-multi-tenancy package. https://github.com/hieuhani/nuxt-multi-tenancy
export default <RouterOptions>{
routes: (_routes) => {
const { ssrContext } = useNuxtApp()
let subdomain = useRequestEvent()?.context?.subdomain
if (ssrContext?.event.context.subdomain) subdomain = ssrContext?.event.context.subdomain

if (subdomain) {
const userRoute = _routes.filter((i) => i.path.includes("/platform/:platformUrl"))
const userRouteMapped = userRoute.map((i) => ({
...i,
path: i.path === "/platform/:platformUrl" ? i.path.replace("/platform/:platformUrl", "/") : i.path.replace("/platform/:platformUrl/", "/"),
}))

return userRouteMapped
}
},
}
export default <RouterOptions>{
routes: (_routes) => {
const { ssrContext } = useNuxtApp()
let subdomain = useRequestEvent()?.context?.subdomain
if (ssrContext?.event.context.subdomain) subdomain = ssrContext?.event.context.subdomain

if (subdomain) {
const userRoute = _routes.filter((i) => i.path.includes("/platform/:platformUrl"))
const userRouteMapped = userRoute.map((i) => ({
...i,
path: i.path === "/platform/:platformUrl" ? i.path.replace("/platform/:platformUrl", "/") : i.path.replace("/platform/:platformUrl/", "/"),
}))

return userRouteMapped
}
},
}
4 replies
NNuxt
Created by patchamamma on 9/8/2024 in #❓・help
Nuxt Plugin using `useCookie` composable error.
Hi, I have a custom Auth fetch nuxt Plugin for fetching data behind a authentication. But I keep getting errors about using Nuxt composables. I am using the useCookie composable. How should I run this function?: 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.
[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.
My custom fetch plugin:
import { useAuthStore } from '~/store/auth';

export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
const store= useAuthStore()

const $authFetch = $fetch.create({
baseURL: config.public.apiBaseURL,
onRequest: async function ({request, options, error}) {

let userSession = useCookie('authToken').value;

if(!userSession?.token || (!userSession?.expiration || new Date(userSession.expiration) <= new Date())) {
console.log("RETRIEVE A NEW TOKEN PLEASE:")
const refreshed = await store.refreshTokenAction();
if(!refreshed) throw new Error('Token refresh failed. Aborting request.');
}
// Retrieve again, I could use refreshCookie()
userSession = useCookie('authToken').value;

if (userSession.token) {
options.headers = options.headers || {}
options.headers.Authorization = `Bearer ${userSession.token}`
}
},
onRequestError({ request, options, error }) {
},
onResponseError({ request, response, options }) {
}
})
return { provide: { authFetch: $authFetch }
}
})
import { useAuthStore } from '~/store/auth';

export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
const store= useAuthStore()

const $authFetch = $fetch.create({
baseURL: config.public.apiBaseURL,
onRequest: async function ({request, options, error}) {

let userSession = useCookie('authToken').value;

if(!userSession?.token || (!userSession?.expiration || new Date(userSession.expiration) <= new Date())) {
console.log("RETRIEVE A NEW TOKEN PLEASE:")
const refreshed = await store.refreshTokenAction();
if(!refreshed) throw new Error('Token refresh failed. Aborting request.');
}
// Retrieve again, I could use refreshCookie()
userSession = useCookie('authToken').value;

if (userSession.token) {
options.headers = options.headers || {}
options.headers.Authorization = `Bearer ${userSession.token}`
}
},
onRequestError({ request, options, error }) {
},
onResponseError({ request, response, options }) {
}
})
return { provide: { authFetch: $authFetch }
}
})
example page that retrieves the data using the authFetch.
<script lang="ts" setup>
const { data, error } = await useAuthFetch(`user/blog/${blogGuid}`);
<script lang="ts" setup>
const { data, error } = await useAuthFetch(`user/blog/${blogGuid}`);
Does somebody know how I can fix this? This might be a SRR issue?
7 replies
NNuxt
Created by patchamamma on 4/24/2024 in #❓・help
Fetch Data even on page reload using custom Fetch Composable
I am trying to fetch data in a page. I am using a custom Fetch composable. But the fetch seems only to work when I navigate to the page using route links. This page uses a middleware but I think this is not the main concern
<script setup>
definePageMeta.....

const {data: data, pending: pending} = await useAuthFetch('/vendor/me');
<script setup>
definePageMeta.....

const {data: data, pending: pending} = await useAuthFetch('/vendor/me');
composable useAuthFetch:
import type { UseFetchOptions } from 'nuxt/app';

export function useAuthFetch<T>(
url: string | (() => string),
options: UseFetchOptions<T> = {}
) {
return useFetch(url, {
...options,
$fetch: useNuxtApp().$authFetch,
})
}
import type { UseFetchOptions } from 'nuxt/app';

export function useAuthFetch<T>(
url: string | (() => string),
options: UseFetchOptions<T> = {}
) {
return useFetch(url, {
...options,
$fetch: useNuxtApp().$authFetch,
})
}
9 replies