question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItΒ collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

middleware error 'The edge runtime does not support Node.js 'crypto' module.'

See original GitHub issue

I’m trying to use middleware for protecting routes, but when running the NextJS, it returns an error

image

NOTE: the middleware is not being used as a edge function. ONLY as a checkpoint for protected routes


packages

  • next: ^12.3.0
  • iron-session: ^6.2.1
  • react: ^18.2.0

file structure

.
β”œβ”€β”€ next-env.d.ts
β”œβ”€β”€ next.config.js
β”œβ”€β”€ package-lock.json
β”œβ”€β”€ package.json
β”œβ”€β”€ public/
β”œβ”€β”€ src
β”‚Β Β  β”œβ”€β”€ components/
β”‚Β Β  β”œβ”€β”€ lib/
β”‚Β Β  β”‚Β Β  └── AuthSession
β”‚Β Β  β”‚Β Β   Β Β  └── index.ts             # contains helper functions for iron-session. obtained from iron-session README
β”‚Β Β  β”œβ”€β”€ middleware.ts                # middleware used for protecting routes
β”‚Β Β  β”œβ”€β”€ pages
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ 404/
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ _app.tsx
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ _document.tsx
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ api/
β”‚Β Β  β”‚Β Β  β”‚Β Β  β”œβ”€β”€ auth/
β”‚Β Β  β”‚Β Β  β”‚Β Β  β”‚Β Β  β”œβ”€β”€ login.ts          # create session using iron-session if the user is authenticated
β”‚Β Β  β”‚Β Β  β”‚Β Β  β”‚Β Β  β”œβ”€β”€ logout.ts         # destroy iron-session session
β”‚Β Β  β”‚Β Β  β”‚Β Β  β”‚Β Β  β”œβ”€β”€ session.ts        # return iron-session if authenticated, else return empty strings
β”‚Β Β  β”‚Β Β  β”‚Β Β  β”‚Β Β  └── unauthorized.ts   # return message the request url is unauthorized
β”‚Β Β  β”‚Β Β  β”‚Β Β  └── summary.ts            # get summary of a system. REQUIRES authentication
β”‚Β Β  β”‚Β Β  └── index.tsx
β”‚Β Β  └── utils/
β”œβ”€β”€ tsconfig.json
└── tsconfig.tsbuildinfo

21 directories, 43 files

files

src/lib/AuthSession/index.ts

/* eslint-disable @typescript-eslint/return-await */
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-explicit-any */
// this file is a wrapper with defaults to be used in both API routes and `getServerSideProps` functions
import type { IronSessionOptions } from 'iron-session';
import { withIronSessionApiRoute, withIronSessionSsr } from 'iron-session/next';
import {
  GetServerSidePropsContext,
  GetServerSidePropsResult,
  NextApiHandler,
  NextApiRequest,
} from 'next';

/**
 * Iron session data format to be used
 */
export interface IAuthSession {
  ipAddress: string;
  port: string;
  password: string;
}

const ironSessionTTL = 30 * 60;

/**
 * Iron session configs
 */
export const sessionOptions: IronSessionOptions = {
  // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
  password: process.env.SECRET_COOKIE_PASSWORD as string,
  cookieName: 'iron-session/pihole/auth',
  ttl: ironSessionTTL,
  // https://github.com/vvo/iron-session#ironoptions
  cookieOptions: {
    // secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
    secure: process.env.NODE_ENV === 'production',
    // https://github.com/vvo/iron-session#session-cookies
    // maxAge: undefined // session expires when closing window/tab.
  },
};

// This is where we specify the typings of req.session.*
declare module 'iron-session' {
  interface IronSessionData {
    authSession: IAuthSession;
  }
}

export function withSessionRoute(handler: NextApiHandler) {
  return withIronSessionApiRoute(handler, sessionOptions);
}

export function withSessionSsr<P extends Record<string, unknown> = Record<string, unknown>>(
  handler: (
    context: GetServerSidePropsContext,
  ) => GetServerSidePropsResult<P> | Promise<GetServerSidePropsResult<P>>,
) {
  return withIronSessionSsr(handler, sessionOptions);
}

src/middleware.ts

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getIronSession } from 'iron-session';

import { sessionOptions } from '@lib/AuthSession';

export async function middleware(req: NextRequest) {
  const res = NextResponse.next();
  const { authSession } = await getIronSession(req, res, sessionOptions);

  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  if (authSession === undefined) {
    return NextResponse.redirect(new URL('/api/auth/unauthorized', req.url));
  }
  return res;
}

export const config = {
  matcher: ['/api/summary'],
};


question

Is there a way to use NextJS middleware to protect routes using iron-session

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6

github_iconTop GitHub Comments

3reactions
firmanjmlcommented, Sep 18, 2022

@Clumsy-Coder I got this fixed by putting sessionOptions on other files. Not sure why that happen but it work…

0reactions
Clumsy-Codercommented, Sep 18, 2022

Can you give me an example? Thanks.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Next.js middleware Module not found: Can't resolve 'fs'
The Edge Runtime, which is used by Next.js Middleware, does not support Node.js native APIs. From the Edge Runtime documentation:.
Read more >
Using Node.js Modules in Edge Runtime - Next.js
The code in your Middleware or your Edge API Routes is using a feature from Node.js runtime. However, the Edge Runtime does not...
Read more >
Understanding Edge support for Node.js modules - Apigee Docs
The Node.js runtime flags such as "harmony-proxies" are not supported. Setting IP connection restrictions on Edge for Private Cloud.
Read more >
Edge Middleware Limitations – Vercel Docs
Node.js APIs are not available Β· Dynamic code execution leads to a runtime error Β· Maximum Execution Duration Β· Memory Β· Code size...
Read more >
Next.js: errors/node-module-in-edge-runtime.md | Fossies
The code in your Middleware or your Edge API Routes is using a feature from Node.js runtime. However, the Edge Runtime does not...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found