Next.js Discord

Discord Forum

In which way I put ID's in my sql db?

Answered
Rex posted this in #help-forum
Open in Discord
RexOP
I have these 4 entities in my db: User, category, OBJ_1, OBJ_2.
I'm wondering if it is better that each entity have autoincrement on their id, or maybe I can update in my code the id for the 2 Objects, in order to have sequentially ID's for every user.
Because my doubt is actually this:
- If one user create an OBJ_1 (or more), it will get ID=1
- Then another user will create the same OBJ_1 and this one will have ID=2 instead of 1
You get me?
Answered by linesofcode
instead of using sequential ids, why not using a uuid?
View full answer

15 Replies

instead of using sequential ids, why not using a uuid?
Answer
Brown bear
Looking at your ERD users & categories to OBJ1 & OBJ2 are one to one relationships. You could just use a composite key of the userid and categoryid unless you specifically need an individual column for this.
@Rex why is better?
Brown bear
Unless you have a specific use case of UUIDs I would use sequential ids
Sequential ids open you up for enumeration attacks and can leak business info
Just something to consider when using easily guessable ids
@linesofcode Sequential ids open you up for enumeration attacks and can leak business info
RexOP
So when I use UUID, I use it on nextjs right? not on the db.
And if so, how can I assure that an ID won't be generated twice?
I was thinking about something like this:

import { v4 as uuidv4 } from 'uuid';

const generateCategoryID = () => {
  const prefix = 'category_';
  const uniqueID = uuidv4().replace(/-/g, ''); // Rimuove i trattini dall'UUID generato
  return `${prefix}${uniqueID}`;
};
It can be done in the db or in nextjs
As long as the unique id scheme is consistent
@linesofcode It can be done in the db or in nextjs
RexOP
how can be done in db?
@Rex how can be done in db?
Google how to do unique ids in a db
It depends on your db too