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
Ping2w 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
!skyfallOP2w ago
got it, thank you!
!skyfall
!skyfallOP2w 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
Ping2w ago
//@ts-ignore Not sure you can do much about this.
!skyfall
!skyfallOP2w ago
Cool, thanks again

Did you find this page helpful?