DEV Community

Gary Menzel
Gary Menzel

Posted on

NodeJS and "crypto" for tokens

If you want to have secure tokens in your action emails that can contain state information then consider using nodejs crypto functions - specifically json-crypto (which is based on the crypto library).

Here are the reasons why:

  • URL safe (so you can use them immediately in your email links)
  • "nonce" based - meaning that each invocation of the encryption function produces a completely different encrypted string (so it is harder to crack)
  • easy to use with your own TOKEN secret (the thing that you protect on your backend that allows the magic to happen)

I wont go into a tutorial because the github repo for json-crypto is easy to follow.

The only thing I will point out is that you don't want to create your TOKEN key/secret each time - you should create that once and store it securely for your application to use it. This is often in environment variables but you could also use a secrets vault of some kind.

The other thing to consider is what you put in your payload - the JSON data that you encrypt. I'd recommend at least a timestamp of some kind (probably just the numeric date from new Date()). With a timestamp you can manage an expiry of the token as well as provide timeline reporting (like how long did it take to get a response). You also want some context regarding what is in the decrypted token. This could be anything like a type or an email or both - or just some other pieces of context that allow the token to be actioned for the specific purpose you want it for (e.g. a subscription confirmation). The payload can be any valid stringified JSON.

Personally, to keep my token smaller, I like to use an array rather than an object. The array then has a standard sequence of information like a type, the timestamp, a version, then other context information applicable to the type based on the version. But you do you - just make sure you follow a standard that you set.

That's about it... Yes - no code on this one again. I don't want to tackle the JS vs TS debate.

Top comments (0)