Correctly mapping UserAttributes to User type #1552
-
Hey there! Hope this is the right place to ask for some assistance! I've been recently using Lucia for a Next.js project I'm taking over and successfully migrated it to V3. I'm now implementing some additional attributes on my user that I would like to have access to after authentication so as to not have to do an additional database query as we already have the user object. My code for mapping attributes from our authentication module is the following: export const auth = new Lucia(adapter, {
sessionExpiresIn: new TimeSpan(2, 'w'),
sessionCookie: {
expires: true,
attributes: {
secure: process.env.NODE_ENV === 'production',
},
},
getUserAttributes: (attributes) => {
return {
username: attributes.username,
email: attributes.email,
credits: attributes.credits,
creditsLifetime: attributes.creditsLifetime,
administrator: attributes.administrator,
}
},
})
// Important! We need to declare this to use custom user attributes.
declare module 'lucia' {
interface Register {
Lucia: typeof Lucia
DatabaseUserAttributes: DatabaseUserAttributes
}
}
// These are passed back on the user during the authentication process.
// Useful to avoid additional DB queries.
export interface DatabaseUserAttributes {
username: string
email: string
credits: number
creditsLifetime: number
administrator: boolean
} Now all is good and well until I want to use these. When I pass the user object around to work with the resulting attributes, I am getting type errors during development that fields do not exist on the User object. However at runtime, these work as intended. Right now I'm sidestepping the issue by proxying an attribute to the any type function Example({ user }: { user: any | null }) {
if (!user)
return
// I really wish we could avoid using "any" here.
const username = user.username || {}
[...]
} This works, but I don't like that user is of type However on the server side function's I'm using I would like to work directly with the export async function GET() {
const { user, session } = await authenticateServer() // user is of type User here.
const credits = user.credits // Throws an error since credits is not available on the user type.
} Any suggestions on how I can work around this effectively? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Should be declare module 'lucia' {
interface Register {
Lucia: typeof auth
DatabaseUserAttributes: DatabaseUserAttributes
}
} |
Beta Was this translation helpful? Give feedback.
Should be
typeof auth
instead oftypeof Lucia