iTranslated by AI
[Quick Tip] A Library for Securely Embedding Information in Web App Session IDs
Introduction
If userId and expiration information can be retrieved by decrypting the session ID, there's no need to link it with an RDBMS or KVS, which results in reduced network I/O and significant performance benefits.
vvo/iron-session seems convenient, but it's intended for use with frameworks like Next.js, Express, and Fastify, and I couldn't find a suitable function if I wanted to use it with AWS Lambda.
The core part for generating session IDs is @hapijs/iron, so by utilizing this, it can be invoked anywhere.
Operation has been confirmed with AWS Lambda runtime Node.js 14.X.
How to Use
I'll borrow from the @hapi/iron official documentation.
yarn add @hapi/iron
Generate a session ID by specifying a string (password) of at least 32 characters. It's best to manage passwords in a keystore.
import * as Iron from '@hapi/iron';
const main = async () => {
const obj = {
a: 1,
b: 2,
c: [3, 4, 5],
d: {
e: 'f',
},
};
const password = 'some_not_random_password_that_is_at_least_32_characters';
try {
const sealed = await Iron.seal(obj, password, Iron.defaults);
console.log(sealed);
const unsealed = await Iron.unseal(sealed, password, Iron.defaults);
console.log(unsealed);
} catch (err) {
console.log(err.message);
}
};
main().then(() => console.log('Success!'));
$ yarn ts-node src/h-api-iro/index.ts
# seal
Fe26.2**70a5e00e53b52fc23f74487a8c29ce555343a4b137e61377f1811a8ec3c7f332*hpCHKzlUapLmHsZF7qCHgQ*OcUgZ5TNIZagZftUeDGSrQIVrN5LK9pOONXyHj6S6DfUi8RZi3eu3Tc4rcpftra**a13a0e731e45fdfc4287a95cdb7aac09fc0db10dd0a023ea735ff180bcee0457*cksLUdsRDoiKtanQWzNXt_KmL_VDBCsIuLt0PI0mrYY
# unseal
{ a: 1, b: 2, c: [ 3, 4, 5 ], d: { e: 'f' } }
Of course, it also works on AWS Lambda (Node 14.X).

Lastly
If I've used it incorrectly, please let me know.
Discussion