New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

csrf-edge

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

csrf-edge

Primary logic behind CSRF tokens for Next.js Edge runtime

  • 0.1.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
decreased by-100%
Maintainers
1
Weekly downloads
 
Created
Source

CSRF-Edge

CSRF-Edge is CSRF protection middleware for Next.js 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
  • 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 CSRF-Edge, first add it as a dependency to your app:

npm install csrf-edge

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

// middleware.js

import csrf from 'csrf-edge';
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);
  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: 60 * 60 * 12,
    domain: '',
    secure: true,
    httpOnly: true,
    sameSite: 'String'
  },
  ignoreMethods: ['GET', 'HEAD', 'OPTIONS'],
  saltByteLength: 8,
  secretByteLength: 8,
  token: {
    responseHeader: 'x-csrf-token',
    value: null
  }
}

TODO:

  • Add details to error response
  • Handle malformed inputs
  • Typescript support
  • Use session cookie

Keywords

FAQs

Package last updated on 02 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