Coder Social home page Coder Social logo

casper64 / next-csrf Goto Github PK

View Code? Open in Web Editor NEW

This project forked from juanbzpy/next-csrf

0.0 0.0 0.0 976 KB

CSRF mitigation for Next.js

Home Page: https://npm.im/next-csrf

License: MIT License

JavaScript 44.08% TypeScript 46.43% CSS 9.49%

next-csrf's Introduction

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

next-csrf's People

Contributors

dependabot[bot] avatar juanbzpy avatar revolunet avatar thegoleffect avatar yuriharrison avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.