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
There is no minimum degree of entropy mandated by the Web Cryptography specification. User agents are instead urged to provide the best entropy they can when generating random numbers, using a well-defined, efficient pseudorandom number generator built into the user agent itself, but seeded with values taken from an external source of pseudorandom numbers, such as a platform-specific random number function, the Unix /dev/urandom device, or other source of random or pseudorandom data.
🌐
npm
npmjs.com › package › crypto-random-string
crypto-random-string - npm
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%
🌐
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.
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>
🌐
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"));
Find elsewhere
🌐
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.
🌐
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 ...
🌐
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.
🌐
CoreUI
coreui.io › answers › how-to-generate-random-strings-in-node-js
How to generate random strings in Node.js · CoreUI
November 17, 2025 - Use crypto.randomBytes() with toString() to generate cryptographically secure random strings in Node.js for tokens and IDs.
🌐
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....
🌐
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.
🌐
GitHub
gist.github.com › dchest › 751fd00ee417c947c252
Generates cryptographically secure uniform random string in browsers and Node.js [IN DEVELOPMENT] · GitHub
Clone this repository at &lt;script src=&quot;https://gist.github.com/dchest/751fd00ee417c947c252.js&quot;&gt;&lt;/script&gt; Save dchest/751fd00ee417c947c252 to your computer and use it in GitHub Desktop. Download ZIP · Generates cryptographically secure uniform random string in browsers and Node.js [IN DEVELOPMENT] Raw ·
🌐
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 ...
🌐
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 ...