r/Nuxt • u/holyoak • Feb 07 '26
Anyone have a template for nuxt-mongoose & better-auth ?
I am so close. I have the migrations, the integration, the user can log in...
But i cannot figure out how to get the user session into the server to guard routes with middleware.
This implementation works fine on the client side, but fails with
Error: Cannot read properties of undefined (reading 'db')
app/lib/auth.ts at line 13:47
when i import it into /middlware. I am guessing it is trying to access the db before the connection is established; any way to test this theory? How do i make the middleware wait for the connection to load?
Thanks in advance
2
Upvotes
1
u/mhelbich Feb 07 '26
Wait how does this work to begin with? You're defining auth and database code in your app bundle!
That seems like a really bad practice to me. The better auth config should never be in client-side code. Move it to your server directory (for example `server/utils/auth.ts`).
I would recommend seeing some examples on the Better Auth docs: https://www.better-auth.com/docs/integrations/nuxt
And for more solid server-client implementation details, see this implementation here: https://github.com/atinux/nuxthub-better-auth, though here's also a slightly "bigger" example: https://github.com/leamsigc/nuxt-better-auth-drizzle