Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

edge-csrf

Package Overview
Dependencies
Maintainers
1
Versions
35
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

edge-csrf

CSRF protection for Next.js middleware

  • 0.1.3-ts
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.7K
decreased by-47.08%
Maintainers
1
Weekly downloads
 
Created
Source

Edge-CSRF

Edge-CSRF is CSRF protection for Next.js middleware that runs in the edge runtime.

This library uses the cookie strategy from expressjs/csurf and the crypto logic from pillarjs/csrf except it only uses Next.js edge runtime dependencies so it can be used in Next.js middleware.

Features

  • Runs in edge runtime
  • Implements cookie strategy from expressjs/csurf and the crypto logic from pillarjs/csrf
  • Gets token from HTTP request header (x-csrf-token) or from request body field (csrf_token)
  • Handles form-urlencoded or json-encoded HTTP request bodies
  • Customizable cookie options

Quickstart

To use Edge-CSRF, first add it as a dependency to your app:

npm install edge-csrf

Next, create a middleware file (middleware.js) for your project and add the Edge-CSRF middleware:

// middleware.js

import csrf from 'edge-csrf';
import { NextResponse } from 'next/server';

// initalize protection function
const csrfProtect = csrf();

export async function middleware(request) {
  const response = NextResponse.next();

  // csrf protection
  const csrfError = await csrfProtect(request, response);

  // check result
  if (csrfError) {
    const url = request.nextUrl.clone();
    url.pathname = '/api/csrf-invalid';
    return NextResponse.rewrite(url);
  }
    
  return response;
}

Next, create a handler to return CSRF error messages to the user:

// pages/api/csrf-invalid.js

export default function handler(req, res) {
  res.status(403).send('invalid csrf token');
}

Now, all HTTP submission requests (e.g. POST, PUT, DELETE, PATCH) will be rejected if they do not include a valid CSRF token. To add the CSRF token to your forms, you can fetch it from the x-csrf-token HTTP response header server-side or client-side. For example:

// pages/my-form.js

export function getServerSideProps({ res }) {
  const csrfToken = res.getHeader('x-csrf-token');
  return {props: { csrfToken }};
}

export default function MyFormPage({ csrfToken }) {
  return (
    <form>
      <input type="hidden" value={csrfToken}>
      <input type="submit">
    </form>
  );
}

Configuration

// default config

{
  cookie: {
    name: '_csrfSecret',
    path: '/',
    maxAge: null,
    domain: '',
    secure: true,
    httpOnly: true,
    sameSite: 'strict'
  },
  ignoreMethods: ['GET', 'HEAD', 'OPTIONS'],
  saltByteLength: 8,
  secretByteLength: 18,
  token: {
    responseHeader: 'x-csrf-token',
    value: null
  }
}

TODO:

  • Add details to error response
  • Typescript support

Keywords

FAQs

Package last updated on 13 Jul 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc