Next.js Discord

Discord Forum

Generating unique session tokens in a postgres db

Unanswered
declspecl posted this in #help-forum
Open in Discord
Hi all! Quick question.

I'm using prisma orm and I have a schema that looks like this:
model User {
    id           Int                   @id @default(autoincrement())
    username     String                @unique
    password     String
    sessionToken String                @unique
}

and I was thinking of how to generate unique session tokens efficiently. The only approach I could think of was something like this which would likely be put in my middleware as well as a server action on initial sign up:
while (true) {
    const newToken = generateNewToken();

    const userWithToken = await prisma.user.findFirst({
        where: {
            sessionToken: newToken
        }
    });

    // no collision
    if (userWithToken === null) {
        await prisma.user.update({
            where: {
                id: myUserId
            },
            data: {
                sessionToken: newToken
            }
        });

        break;
    }
}

but this is two queries to my database AND has the (statistically improbably) possibility of needing to run twice, thrice, etc. Is there a better way? How do you guys do it? Thanks!

2 Replies

while you can do while loop, the better solution is get a lib that wont get colisions to begin with (for example: [@paralleldrive/cuid2](https://www.npmjs.com/package/@paralleldrive/cuid2) if just random strings - can also make longer if needed)
and if you still get colision from cuid2 (so rare you shouldn't ever get it even if somehow do this much), your database erroring out from the unique should be fine