Replies: 1 comment
-
|
Auth.js v5 works with Blitz, but since Blitz has its own session management, you need to bridge the two. The key insight is that Auth.js v5 handles the authentication (verifying identity via email magic links), while Blitz sessions handle the authorization (keeping the user logged in across requests). Here's the approach that works: 1. Set up Auth.js v5 in your API routes Create the Auth.js handler at import NextAuth from "next-auth"
import Resend from "next-auth/providers/resend"
export const { handlers, auth, signIn } = NextAuth({
providers: [
Resend({
from: "noreply@yourdomain.com",
}),
],
callbacks: {
async signIn({ user }) {
// Auth.js verified the magic link - user.email is confirmed
return true
},
},
})2. Bridge Auth.js into Blitz sessions The trick is to create a Blitz session after Auth.js confirms the login. Use the // src/pages/api/auth/callback.ts (or inside your [...nextauth] callbacks)
import { api } from "src/blitz-server"
callbacks: {
async signIn({ user }) {
return true
},
async jwt({ token, user, trigger }) {
if (trigger === "signIn" && user?.email) {
// Store the email in the JWT so we can create a Blitz session
token.email = user.email
}
return token
},
}3. Create a Blitz mutation to finalize the session After Auth.js redirects back, call a Blitz mutation from the client to establish the Blitz session: // src/mutations/loginWithAuthJs.ts
import { resolver } from "@blitzjs/rpc"
import db from "db"
import { SecurePassword } from "@blitzjs/auth/secure-password"
export default resolver.pipe(async (input: { email: string }, ctx) => {
const user = await db.user.upsert({
where: { email: input.email },
update: {},
create: { email: input.email, role: "USER" },
})
await ctx.session.$create({
userId: user.id,
role: user.role,
})
return user
})4. On the client, after Auth.js callback: import { useSession } from "next-auth/react"
import { useMutation } from "@blitzjs/rpc"
import loginWithAuthJs from "src/mutations/loginWithAuthJs"
function AuthCallback() {
const { data: authSession } = useSession()
const [loginMutation] = useMutation(loginWithAuthJs)
useEffect(() => {
if (authSession?.user?.email) {
loginMutation({ email: authSession.user.email })
.then(() => router.push("/dashboard"))
}
}, [authSession])
return <div>Completing login...</div>
}The pattern is essentially: Auth.js handles identity verification, then you immediately create a Blitz session from the verified identity. This way you get magic links from Auth.js v5 while keeping all of Blitz's |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Has anyone implemented this? BlitzJS docs are using the outdated Next-auth v4 library. I need to use Email auth + magic links. As I understand, I need to call a callback at some point that would create a session in BlitzJS, but I can't understand how to do that with AuthJS v5. Thank you.
Beta Was this translation helpful? Give feedback.
All reactions