How to Create Unique Voucher Codes That Don't Collide

My first problem was how to generate the coupon codes. Initially, I wanted a way to put that functionality in the database. But because I want this working superfast and I don't have the luxury of figuring out all the quirks of getting it to work in the database, I opted for a server function.

To generate the codes I'll be using the voucher-code-generator-js library from Voucherify. It's a cool little npm package and it works. I found it on the "How to generate unique coupon codes?" blog post.

The idea here is that once a code has been generated, I should check the db to see if it exists and if it does, then generate another code and repeat until I have a code that does not exist. When I get that, I then insert the code into the db.