middleware error 'The edge runtime does not support Node.js 'crypto' module.'
See original GitHub issueIβm trying to use middleware for protecting routes, but when running the NextJS, it returns an error
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:
- Created a year ago
- Comments:6
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@Clumsy-Coder I got this fixed by putting sessionOptions on other files. Not sure why that happen but it workβ¦
Can you give me an example? Thanks.