#Nuxt Auth Struggling With BaaS
12 messages · Page 1 of 1 (latest)
this is another file
Based on the knowledge sources provided and your question about implementing authentication with Pocketbase JS SDK in a Nuxt application, I can offer some insights and suggestions to help address your issue.
The server-side error you're encountering in your middleware is likely related to how you're handling authentication checks and redirections. Here are some points to consider:
-
Server-side navigation:
The error you're seeing might be due to attempting to usenavigateToon the server side. As mentioned in the Stack Overflow post, server-side navigation can be tricky. Instead of usingnavigateTo, you could try returning a redirect response directly:if (import.meta.server) { try { await pb.collection('users').authRefresh(); } catch (error) { if (authRequired) { const response = event.node.res; if (!response.headersSent) { response.writeHead(302, { Location: '/login' }); response.end(); } return; } } } -
Handling authentication in middleware:
The Nuxt documentation on authentication suggests using auseUserSessioncomposable to check if the user is logged in. You might want to consider adapting this approach to work with Pocketbase:export default defineNuxtRouteMiddleware(() => { const { loggedIn } = useUserSession() if (!loggedIn.value) { return navigateTo('/login') } })
-
Protecting API routes:
Make sure you're also protecting your API routes on the server side. The Nuxt documentation provides an example of how to do this:export default defineEventHandler(async (event) => { const { user } = await requireUserSession(event) // Your protected API logic here }); -
Using cookies for authentication:
If you're using cookies for authentication, make sure they're being properly set and read. The Stack Overflow post on using cookies in Nuxt 3 provides some insights on how to work with cookies in both API routes and middleware. -
Avoiding glitchy redirects:
As mentioned in another Stack Overflow post, usingnavigateTo()instead ofrouter.push()in your middleware can help avoid glitchy-looking redirects.
Remember that implementing authentication, especially with server-side rendering, can be complex. If you continue to face issues, you might want to consider using a more Nuxt-specific authentication solution or seeking help from the Nuxt community as suggested in the Nuxt documentation on getting help.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
// usePocketBase.js
import PocketBase from 'pocketbase';
import { COLLECTIONS } from '~/utils/constants';
export const usePocketBase = () => {
const nuxtApp = useNuxtApp();
// Check if the instance already exists in the app context
if (!nuxtApp._pbInstance) {
const config = useRuntimeConfig();
nuxtApp._pbInstance = new PocketBase(config.public.pocketbaseUrl);
// --- Cookie Forwarding (Server-Side) ---
if (import.meta.server) {
const request = nuxtApp.ssrContext.event.node.req;
nuxtApp._pbInstance.beforeSend = (url, options) => {
if (request.headers.cookie) {
if (!options.headers) {
options.headers = {};
}
options.headers.cookie = request.headers.cookie; // Forward the cookie
}
return { url, options };
};
}
// --- Load from Cookie (Client-Side) ---
if (import.meta.client) {
const authCookie = useCookie('pb_auth', {
maxAge: 7 * 24 * 60 * 60,
path: '/',
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax'
});
if (authCookie.value) {
try{
nuxtApp._pbInstance.authStore.save(authCookie.value.token, authCookie.value.record);
} catch(error){
console.error("Error loading auth from cookie", error)
authCookie.value = null; // Clear invalid cookie
}
}
}
}
// Return the instance from the app context
return nuxtApp._pbInstance;
};```
@young locust Kapa.ai is still learning and improving, please let me know how I did by reacting below.
the problem also occurs if i directly try to go to /dashboard route
which redirects me back to /login as it should without any prior authentication but these are the logs on console
usePocketBase.js file
useAuth.js file
the error in ques when i go to /dashboard route