Auth management when you have separate backend
Unanswered
Cape lion posted this in #help-forum
Cape lionOP
Hi. I want to use Next.js as the frontend and am using Nestjs as my backend API. Since, unlike React SPAs, it has both server-side (server components and actions) and client-side to make API calls, I am struggling how to understand implement auth and role based access, including routing control (proxy.ts is needed most likely). How should I go about it in Next.js without causing unwanted flash of incorrect auth state? Should I use sessions or a session+ JWT hydrid approach? I have pasted the primsa model used by the Backend API for authentication so far.
enum Role {
USER
ADMIN
}
enum OAuthProvider {
GOOGLE
}
model User {
id String @id @default(uuid())
email String @unique
// Null for accounts created via OAuth only, e.g. Google, that never set a password.
passwordHash String?
name String
role Role @default(USER)
emailVerifiedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
oauthAccounts OAuthAccount[]
@@map("users")
}
model OAuthAccount {
id Int @id @default(autoincrement())
userId String
provider OAuthProvider
providerAccountId String
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
@@index([userId])
@@map("oauth_accounts")
}6 Replies
Cape lionOP
Bumping this post
my suggestion is to use better-auth
@strikx my suggestion is to use better-auth
Cape lionOP
if you use better-auth, how do you use session info e,g user and its roles on the Next.js server-side e.g. proxy.ts, server components and actions when you have a separate backend API?
@strikx https://better-auth.com/docs/plugins/jwt
Cape lionOP
Why use jwt instead session? Wouldn't that require me to pass token in authorization header in client and server side?
@Cape lion if you use better-auth, how do you use session info e,g user and its roles on the Next.js server-side e.g. proxy.ts, server components and actions when you have a separate backend API?
Yellow Wagtail
you can just set up better-auth in your Next.js app too, and set the base URL and BETTER_AUTH_URL to your API. It might create CORS issues, so you need to set up CORS properly.
or, you can just set up better-auth in your Next.js app with the same db. It won't create any conflict since both follow the same pattern.
or, you can just set up better-auth in your Next.js app with the same db. It won't create any conflict since both follow the same pattern.