Naive Puppets Marching


    1.0.1 • Public • Published

    csurf with login tokens

    Node.js CSRF protection middleware.

    Requires cookie-parser to be initialized first.

    This module is based off of csurf and uses an almost identical API, however it uses an existing login token instead of creating a new token and cookie. The security implications of doing this are discussed here.


    $ npm install csurf-login-token --save


    const csurf = require('csurf-login-token');

    csurf(cookieName[, options])


    The name of the cookie where the login token is stored. There are many online tutorials on how to generate this securely, please do so.


    The csurf function takes an optional options object that may contain any of the following keys:


    An array of the methods for which CSRF token checking will disabled. Defaults to ['GET', 'HEAD', 'OPTIONS'].


    Provide a function that the middleware will invoke to read the token from the request for validation. The function is called as value(req) and is expected to return the token as a string.

    The default value is a function that reads the token from the following locations, in order:

    • req.body._csrf - typically generated by the body-parser module.
    • req.query._csrf - a built-in from Express.js to read from the URL query string.
    • req.headers['csrf-token'] - the CSRF-Token HTTP request header.
    • req.headers['xsrf-token'] - the XSRF-Token HTTP request header.
    • req.headers['x-csrf-token'] - the X-CSRF-Token HTTP request header.
    • req.headers['x-xsrf-token'] - the X-XSRF-Token HTTP request header.

    Examples, Ignoring Routes, Custom error handling

    Since the API is identical, please check the examples in the CSURF repo.

    How it works

    The CSRF token is generated by hashing the login cookie using the SHA3-512 algorithm. As long as the login token is long enough and generated using a cryptographically secure pseudorandom generator, it's hash will be too. This is perfectly safe because by definition, hashes are one way functions so the login token cannot be found in a reasonable time period. For more information please see this post.

    Note: If there is no login token present the same error (EBADCSRFTOKEN) will be thrown as if the validation failed.


    • All the benefits of cookie based CSRF tokens
    • Prevents having to store an extra cookie on the client reducing network traffic on every request
    • If the login token is indeed unique per session (even between the same users) then each csrf token will be unique per session allowing for multiple tabs to be open without causing issues




    npm i csurf-login-token

    DownloadsWeekly Downloads






    Unpacked Size

    6.05 kB

    Total Files


    Last publish


    • jbis9051