Setting an `apiKey` additional field on users

I'm trying to add an apiKey field to my users, like so:
import { betterAuth } from "better-auth";

export const auth = betterAuth({
// ...
user: {
additionalFields: {
role: {
type: "string",
required: true,
input: false, // don't allow user to set API key themselves
},
},
},
});
import { betterAuth } from "better-auth";

export const auth = betterAuth({
// ...
user: {
additionalFields: {
role: {
type: "string",
required: true,
input: false, // don't allow user to set API key themselves
},
},
},
});
But I'm not sure how to generate an unique key for each user on signup. How can I do this?
Solution:
I'm going assume you're using the apiKey plugin.
But I'm not sure how to generate an unique key for each user on signup. How can I do this?
Use database hooks: https://www.better-auth.com/docs/concepts/database#2-after-hook...
No description
Jump to solution
5 Replies
Solution
Ping
Ping5mo ago
I'm going assume you're using the apiKey plugin.
But I'm not sure how to generate an unique key for each user on signup. How can I do this?
Use database hooks: https://www.better-auth.com/docs/concepts/database#2-after-hook Use an after hook on user create. ^^ Then create an api key. Here's an example:
No description
!skyfall
!skyfallOP5mo ago
got it, thank you!
!skyfall
!skyfallOP5mo ago
One more question: I'm using Drizzle too and I noticed that I have to make the API Key column nullable to allow creating users. It works, but how do you deal with TypeScript complaining that apiKey could be undefined even though it definitely won't?
Ping
Ping5mo ago
//@ts-ignore Not sure you can do much about this.
!skyfall
!skyfallOP5mo ago
Cool, thanks again

Did you find this page helpful?