Create Unique API key in Node to store in Redis
Asked Answered
L

3

5

I'm building an API in Node and looking to store the API key/access token in Redis.

How best can I generate a unique API key/access token to store in Redis as the key and an email address as the value?

Does Redis have an inbuilt function for generating unique ids with certain length and character set or how best should I tackle this?

Thank you!

Leopold answered 14/12, 2014 at 6:59 Comment(1)
I'd say use UUID: github.com/broofa/node-uuidAntichlor
A
3

The INCR command of Redis allows you to increment a counter and so generate unique numeric IDs. As far as I know, there is not other built-in feature in redis to generate a unique ID.

If you need a more complex ID, you will have to generate it in node, like said Brendan in the comments. You could combine redis INCR to generate numeric values and then provide it to a library like hashids.

Anecdotic answered 14/12, 2014 at 11:20 Comment(1)
Redis also works much better with simple ints than hashes. It helps in the storage and query performance.Crispate
S
3

A good solution for unique Ids in redis, especially with multiple redis instances is to use a combination of a domain name and uuid (see Brendan's response). So, for an application that inserts new users with a domain name of 'User' you would create an id like this:

var uuid = require('node-uuid');

var createUniqueId = function() {
    return 'User:' + uuid.v4();
};

Other examples of this approach are described here for leveldb but applicable to redis.

Syndactyl answered 15/12, 2014 at 21:18 Comment(0)
N
3

Like Darryl West said, you should definitely generate the tokens in node. However, if you don't want to take a dependency on uuid then you can always use node's built-in crypto to create random bytes and convert to a string.

var crypto = require('crypto')

function generateToken() {
  return crypto.randomBytes(48).toString('base64');
}

See crypto.randomBytes(size[, callback]) for more info.

Newland answered 6/8, 2015 at 4:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.