Try crypto.randomBytes():

require('crypto').randomBytes(48, function(err, buffer) {
  var token = buffer.toString('hex');
});

The 'hex' encoding works in node v0.6.x or newer.

Updates for ES2021+ using Buffer

import {randomBytes} from "node:crypto";

function tokenGenerate(length=56) {
    return Buffer.from(randomBytes(length)).toString('hex');
}
Answer from thejh on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Crypto › getRandomValues
Crypto: getRandomValues() method - Web APIs | MDN
getRandomValues() is the only member of the Crypto interface which can be used from an insecure context. ... An integer-based TypedArray, that is one of: Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, BigUint64Array (but not Float16Array, Float32Array nor Float64Array). All elements in the array will be overwritten with random numbers. The same array passed as typedArray but with its contents replaced with the newly generated random numbers.
🌐
npm
npmjs.com › package › crypto-random-string
crypto-random-string - npm
May 10, 2022 - Generate a cryptographically strong random string · Can be useful for creating an identifier, slug, salt, PIN code, fixture, etc. Works in Node.js and browsers. npm install crypto-random-string ·
      » npm install crypto-random-string
    
Published   May 10, 2022
Version   5.0.0
Author   Sindre Sorhus
🌐
GitHub
gist.github.com › aryomuzakki › b0fa350abcfa93598c8ce57883933d38
Generate Random Number and String in Javascript, using Math.random(), Node JS Crypto (server side), or Web Crypto API (client side / browser) · GitHub
Generate Random Number and String in Javascript, using Math.random(), Node JS Crypto (server side), or Web Crypto API (client side / browser) - crypto-random.js
🌐
GitHub
github.com › sindresorhus › crypto-random-string
GitHub - sindresorhus/crypto-random-string: Generate a cryptographically strong random string
Works in Node.js and browsers. ... import cryptoRandomString from 'crypto-random-string'; cryptoRandomString({length: 10}); //=> '2cf05d94db' cryptoRandomString({length: 10, type: 'base64'}); //=> 'YMiMbaQl6I' cryptoRandomString({length: 10, type: 'url-safe'}); //=> 'YN-tqc8pOw' cryptoRandomString({length: 10, type: 'numeric'}); //=> '8314659141' cryptoRandomString({length: 6, type: 'distinguishable'}); //=> 'CDEHKM' cryptoRandomString({length: 10, type: 'ascii-printable'}); //=> '`#Rt8$IK>B' cryptoRandomString({length: 10, type: 'alphanumeric'}); //=> 'DMuKL8YtE7' cryptoRandomString({length: 10, characters: 'abc'}); //=> 'abaaccabac'
Starred by 575 users
Forked by 43 users
Languages   JavaScript 95.0% | TypeScript 5.0% | JavaScript 95.0% | TypeScript 5.0%
Top answer
1 of 2
2

Is this safe enough or am I making a horrible mistake?

Safe enough. Overkill, honestly. The most notable improvement I'd recommend here in particular is hashing the session token before storing it in the DB (or checking it against the DB-stored list of sessions). That way, even if an attacker gets a look at the DB, they couldn't steal somebody else's session. You should also enforce a server-side timeout for sessions, if you're going to have them time out at all.

Of course, there's a ton of other considerations that go into an authentication system (much less authorization). What credentials to use and how to verify them, how to handle loss of credentials (e.g. forgotten password), multi-factor auth, and so much more.

Also, specifically with cookies, you need to make sure your service is secure against CSRF (Cross-Site Request Forgery) attacks. There's a bunch of ways to do that but you do need to do at least one of them.

seems bad to me that it only uses 0-9 characters, it'd probably be much more secure if I used ASCII letters as well

Nope, that's actually pretty irrelevant. 16x UInt32 is 512 bits (64 bytes), which is excessively high entropy for a session token (most are in the 128-256 bits range, and every extra bit doubles the difficulty to brute-force the token). Representing it as decimal digits [0-9] isn't any less secure than representing it as hex [0-9A-F] or base64 [0-9A-Za-z./], and also isn't any more secure than representing it as octal [0-7] or even binary [0-1]. 64 bytes can be 512 binary digits, or 171 octal digits (including two bits of padding), or 155 decimal digits (again including some padding), or 128 hex digits, or 86 base64 digits (including some bits of padding, plus usually it would be further padded with two = for a total length of 88).

You see how the string gets shorter the wider the character set used? Yet they all have the exact same amount of unguessability (entropy).

Now, string concatenation of decimal values (without delimiters or padding) in particular is a bad way to handle this, because it does introduce ambiguities (simple example: the string "101234" could be formed by the numbers "101","234", or "10","1234", or "10","12","34", or... you get the idea), but it still doesn't matter. Even if we assume that the string randomly ended up only 100 digits long - less likely than correctly picking a randomly selected atom of the planet Earth - it would still ludicrously unguessable (279-332 bits of entropy, far stronger than the encryption keys used for financial communications).

2 of 2
2

Here is a simple html web page that uses the javascript Crypto.getRandomValues() function to create a random 32-byte hexadecimal string:

<html lang="en">
<head>
<meta charset="utf-8">
<title>Random String Generator</title>
</head>
<body>
<h3>Random String Generator</h3>

<script>
document.write(bytestohex(window.crypto.getRandomValues(new Uint8Array(32))));

function bytestohex(bytes) {
    var hexstring='', h;
    for(var i=0; i<bytes.length; i++) {
        h=bytes[i].toString(16);
        if(h.length==1) { h='0'+h; }
        hexstring+=h;
    }   
    return hexstring;
}
</script>
</body>
</html>
🌐
QuickRef.ME
quickref.me › home › how to generate a random string using node crypto module in javascript - quickref.me
How to generate a random string using node crypto module in JavaScript - QuickRef.ME
In this Article we will go through how to generate a random string using node crypto module only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.
🌐
DEV Community
dev.to › sean_kegel › quick-tip-use-node-to-create-random-strings-57gf
Quick Tip: Use Node to Create Random Strings - DEV Community
October 7, 2023 - node -e “console.log(require(‘node:crypto’).randomBytes(8).toString(‘hex’))” | pbcopy · Just remember, when using the command from the terminal or REPL, the length passed to randomBytes will be half the length of what is outputted. So if you need a random string of 8 characters, pass 4 as the length. I hope this quick tip was helpful. Let me know if the comments if you’ve seen any optimizations to the code above or if there’s an easier way to generate random strings.
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › node-js-crypto-randombytes-method
Node crypto.randomBytes() Method - GeeksforGeeks
July 12, 2025 - Now, let us understand with the help of the example: ... // Node.js program to demonstrate the // crypto.randomBytes() method // Including crypto module const crypto = require('crypto'); // Calling randomBytes method with callback ...
Find elsewhere
🌐
KindaCode
kindacode.com › article › how-to-easily-generate-a-random-string-in-node-js
3 Ways to Generate Random Strings in Node.js - KindaCode
February 12, 2023 - The example below will generate a random string with a given length. The result will only contain alphabet letters and numbers (a-z, A-Z, 0-9), but you can modify the chars variable as needed. ... // Create a function for reusable perpose const generateRandomString = (myLength) => { const chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890"; const randomArray = Array.from( { length: myLength }, (v, k) => chars[Math.floor(Math.random() * chars.length)] ); const randomString = randomArray.join(""); return randomString; }; // Try it console.log(generateRandomString(10)); console.log(generateRandomString(30));
🌐
Oslo
oslo.js.org › reference › crypto › generateRandomString
generateRandomString()
import { generateRandomString, alphabet } from "oslo/crypto"; // 10-characters long string consisting of the lowercase alphabet and numbers generateRandomString(10, alphabet("a-z", "0-9"));
🌐
Futurestud.io
futurestud.io › tutorials › generate-a-random-string-in-node-js-or-javascript
Generate a Random ID or String in Node.js or JavaScript
February 6, 2020 - Pro - generates URL-friendly, random strings - customizable the string length - expressive interface ... Another option is the usage of Node.js’ crypto module. The Crypto.randomBytes() method generates cryptographically strong pseudo-random data for a given number of bytes.
🌐
Sean Kegel
seankegel.com › quick-tip-use-node-to-create-random-strings
Quick Tip: Use Node to Create Random Strings
July 18, 2024 - const { randomBytes } = ... randomString(8); // string = "df5ec630" A few issues with this is the length passed to the randomBytes method needs to be an even number so it can be divided in half....
🌐
Tabnine
tabnine.com › home page › code › javascript › crypto
crypto.randomBytes JavaScript and Node.js code examples | Tabnine
... // Returns a new random hex string of the given even size. function randomHexString(size) { if (size === 0) { throw new Error('Zero-length randomHexString is useless.'); } if (size % 2 !== 0) { throw new Error('randomHexString size must ...
🌐
Sentry
sentry.io › sentry answers › javascript › generate random string/characters in javascript
Generate random string/characters in JavaScript | Sentry
The generated random number is made cryptographically secure by providing the algorithm with a random initial seed value. The random seed value is obtained from an external source of pseudo-random numbers, such as a platform-specific random number function, hardware events such as mouse movements or key presses, or system events such as disk activity or CPU usage. If you need to generate unique random string ...
🌐
GitHub
gist.github.com › dchest › 751fd00ee417c947c252
Generates cryptographically secure uniform random string in browsers and Node.js [IN DEVELOPMENT] · GitHub
Generates cryptographically secure uniform random string in browsers and Node.js [IN DEVELOPMENT] - randomString.js
🌐
GitHub
gist.github.com › joepie91 › 7105003c3b26e65efcea63f3db82dfba
Secure random values (in Node.js) · GitHub
If you need a random string: You have two good options here, depending on your needs. Use a v4 UUID, with the crypto.randomUUID method. Use a nanoid, using the standalone build of the nanoid library.
🌐
GitHub
gist.github.com › 6174 › 6062387
Generate a random string in JavaScript In a short and fast way! · GitHub
for(var a = ''; r = Math.random() * 42, a.length < 40;) a += r < 10 || r > 16 ? String.fromCharCode(48 + r | 0) : '' ... Using crypto: crypto.randomBytes(32).toString('base64'), adjust the parameter to randomBytes for the length you need.
🌐
Medium
medium.com › @python-javascript-php-html-css › how-to-generate-a-random-5-character-string-in-javascript-f35accc66cbd
How to Use JavaScript to Create a Random String of Five Characters
August 24, 2024 - For instance, using CryptoJS.lib.WordArray.random, you can create a secure random string of specified length, ensuring that it meets the highest standards of randomness and unpredictability. Another advanced technique involves using UUIDs (Universally Unique Identifiers). Libraries like uuid can generate unique strings based on various algorithms, ensuring that the generated strings are not only random but also unique across different systems and contexts.