r/learnjavascript • u/ConfidentWafer5228 • 22h ago
How to store and verify emojis server-side ( MERN stack )
EDIT: Solved ( Also, for anyone having same doubt, make sure to target es2024 or later in ur tsconfig for TS ). Huge Thanks to everyone ❤️ ( ➡️ Pun intended )
I understand that emojis are encoded strings and can be UTF-8, 16 or 32 . But i dont understand how to have consistency on my frontend and backend. Also how does one verify the emoji unicode from client on server.
Basically i want to verify if the unicode is an EMOJI otherwise REJECT the request.
One way i see is storing a predefined Set() of emoji unicodes and checking if the client has sent a valid one. But i feel like there is a better way. What is the usual way?
Please help. Also i watched a short video, it threw some terms like surrogate and white-point something, idk
EDIT: I want to check and pass only the input that has EXACTLY ONE EMOJI
For example--> ✌️ passes but multiple emojis or emojis with text shouldn't pass
1
u/Ok_Car_8951 21h ago
in node 20+ you can check it with regex `/^\p{RGI_Emoji}$/v`, it match full emoji also with skin tone and flags, no need to keep your own Set
1
u/Warm-Republic-1913 15h ago
To answer the encoding part, you do not have to manage UTF-8 versus UTF-16 yourself. JavaScript strings are UTF-16 internally, which is why one emoji can have a length of 2 (a surrogate pair), but JSON and HTTP bodies are sent as UTF-8 and both the browser and Node decode them back to the same string, so the frontend and backend already agree. The /\p{RGI_Emoji}$/v check mentioned above works because it matches one full emoji sequence, including the invisible joiner and variation selector characters. Your ✌️ example is really two code points, a base character plus a variation selector, which is the other reason counting length is unreliable. Two practical notes: the v flag needs Node 20 or newer, and a bare character without the variation selector may be rejected because it is not a fully qualified emoji. Also cap the input length before running the regex, and keep the same check on the server even if the frontend does it, since clients can send anything.
1
u/Own_Giraffe987 20h ago
Using regex is solid, but you'll need to ensure your client sends the input as UTF 8 to avoid mismatches.