npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nmt-next-csrf

v1.0.1

Published

CSRF mitigation library for Next.js

Downloads

3

Readme

next-csrf

Discord

CSRF mitigation for Next.js.

Features

Mitigation patterns that next-csrf implements:

Installation

With yarn:

yarn add next-csrf

With npm:

npm i next-csrf --save

Usage

Create an initialization file to add options:

// file: lib/csrf.js

import { nextCsrf } from "next-csrf";

const { csrf, setup } = nextCsrf({
    // eslint-disable-next-line no-undef
    secret: process.env.CSRF_SECRET,
});

export { csrf, setup };

Protect an API endpoint:

// file: pages/api/protected.js

import { csrf } from '../lib/csrf';

const handler = (req, res) => {
    return res.status(200).json({ message: "This API route is protected."})
}

export default csrf(handler);

Test the protected API route by sending a POST request from your terminal. Since this request doesn't have the proper token setup, it wil fail.

curl -X POST http://localhost:3000/api/protected
>> {"message": "Invalid CSRF token"}

Use an SSG page to set up the token. Usually, you use CSRF mitigation to harden your requests from authenticated users, if this is the case then you should use the login page.

// file: pages/login.js

import { setup } from '../lib/csrf';

function Login() {
    const loginRequest = async (event) => {
        event.preventDefault();
        
        // The secret and token are sent with the request by default, so no extra
        // configuration is needed in the request.
        const response = await fetch('/api/protected', {
            method: 'post'
        });
        
        if (response.ok) {
            console.log('protected response ok');
        }
    }
    
    return (
        <form onSubmit={loginRequest}>
            <label>
                Username
                <input type="text" required />
            </label>
            
            <label>
                Password
                <input type="password" required />
            </label>
            
            <button>Submit</button>
        </form>
    )
}

// Here's the important part. `setup` saves the necesary secret and token.
export const getServerSideProps = setup(async ({req, res}) => {
    return { props: {}}
});

export default Login;

API

nextCsrf(options);

Returns two functions:

  • setup Setups two cookies, one for the secret and other one for the token. Only works on SSG pages.
  • csrf Protects API routes from requests without the token. Validates and verify signatures on the cookies.

options

  • tokenKey (string) The name of the cookie to store the CSRF token. Default is "XSRF-TOKEN".
  • csrfErrorMessage (string) Error message to return for unauthorized requests. Default is "Invalid CSRF token".
  • ignoredMethods: (string[]) Methods to ignore, i.e. let pass all requests with these methods. Default is ["GET", "HEAD", "OPTIONS"].
  • cookieOptions: Same options as https://www.npmjs.com/package/cookie