node-postgres: Doesn't work with next.js Edge runtime

I’m writing an app on next.js which I plan to deploy to CloudFlare Pages + Workers. I know there’s CloudFlare support, but when running the local development server of next.js, I get the following errors:

Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
    at <unknown> (webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/web/globals.js:33)
    at Object.get (webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/web/globals.js:33:19)
    at eval (webpack-internal:///(middleware)/./node_modules/pg/lib/crypto/utils-webcrypto.js:19:36)
    at (middleware)/./node_modules/pg/lib/crypto/utils-webcrypto.js (file:///home/danny/src/project/.next/server/pages/api/manageUser.js:3097:1)
    at __webpack_require__ (file:///home/danny/src/project/.next/server/edge-runtime-webpack.js:37:33)
    at fn (file:///home/danny/src/project/.next/server/edge-runtime-webpack.js:286:21)
    at eval (webpack-internal:///(middleware)/./node_modules/pg/lib/crypto/utils.js:7:22)
    at (middleware)/./node_modules/pg/lib/crypto/utils.js (file:///home/danny/src/project/.next/server/pages/api/manageUser.js:3108:1)
    at __webpack_require__ (file:///home/danny/src/project/.next/server/edge-runtime-webpack.js:37:33)
    at fn (file:///home/danny/src/project/.next/server/edge-runtime-webpack.js:286:21)
    at eval (webpack-internal:///(middleware)/./node_modules/pg/lib/crypto/sasl.js:3:16)

Would it make sense to generalize CloudFlare Workers detection into a broader Edge detection that also includes node edge runtime?

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 12
  • Comments: 37 (23 by maintainers)

Most upvoted comments

I am using Next.js and Drizzle, and get the same: Error: The edge runtime does not support Node.js 'crypto' module. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime

This is sufficent:

import { MiddlewareConfig, NextResponse } from "next/server";
import { PagePath } from "@/enums";
import NextAuth from "next-auth";

const { auth } = NextAuth({ providers: [] });

export const middleware = auth(async (req) => {
	const path = new URL(req.url).pathname;

	const session = await auth();

	const isSigninPage = path === PagePath.SIGNIN.toString();
	const isRootPage = path === PagePath.ROOT.toString();
	const isAPIRoute = path.startsWith("/api");

	if (session && isSigninPage) {
		return NextResponse.redirect(new URL(PagePath.ROOT, req.url));
	}

	if (!session && !(isRootPage || isSigninPage || isAPIRoute)) {
		return NextResponse.redirect(new URL(PagePath.SIGNIN, req.url));
	}
});

export const config: MiddlewareConfig = {
	matcher: ["/((?!api|_next/static|_next/image\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"],
};

BUT you have to ensure that you are using the JWT strategy and never access the DB during the middleware, here is auth.ts:

import NextAuth, { DefaultSession } from "next-auth";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import { getDatabaseClient } from "db/connection";
import { accounts, sessions, users, verificationTokens } from "db/schema";
import { User } from "@/types/database-types";
import { eq } from "drizzle-orm";
import Google from "next-auth/providers/google";
import Resend from "next-auth/providers/resend";

declare module "next-auth" {
	/**
	 * Returned by `auth`, `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
	 */
	interface Session {
		user: User & DefaultSession["user"];
	}
}

export const { handlers, signIn, signOut, auth } = NextAuth({
	adapter: DrizzleAdapter(getDatabaseClient(), {
		usersTable: users,
		accountsTable: accounts,
		sessionsTable: sessions,
		verificationTokensTable: verificationTokens,
	}),
	session: { strategy: "jwt" },
	callbacks: {
		session: async ({ session }) => {
			const db = getDatabaseClient();
			const user = await db.query.users.findFirst({
				where: eq(users.email, session.user.email),
			});

			session.user = { ...user, ...session.user };
			return session;
		},
	},
	providers: [Google, Resend],
});

For those hitting this issue as part of a next-auth / auth js 5 integration, this document helped me understand the situation better: https://authjs.dev/guides/edge-compatibility

“”" PostgreSQL is a database that uses a message-based protocol for communication between a the client and server that is transported via TCP (or Unix) sockets. Raw TCP sockets are one of those Node.js features that are generally not available to edge runtimes. Therefore, on the surface, it seems like it’s not possible to communicate with a PostgreSQL database from JavaScript running on edge runtime. The same goes for many other databases and their respective communication protocols.

As edge runtimes have matured and become more popular, however, people have gotten creative and implemented various solutions to this problem. One such common solution is to put some sort of API server in front of the database whose goal is to translate database queries sent to it via HTTP into a protocol the database can understand. This allows the client side to only have to make HTTP requests to the API server, which is something that every edge runtime supports. “”"

My workaround was to expose an API to pg that an auth.ts callback can hit from edge. I think I’d still prefer using pg in edge runtime (sounds like Brian is close to a solution), but maybe this is working as intended if node-postgres is designed for the node.js runtime, which Vercel’s Edge runtime doesn’t (or only partially) uses

@andyjy when i applied your patch to the crypto file I now get this:

⨯ Error: The edge runtime does not support Node.js 'net' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
    at Object.construct (webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/web/globals.js:37:19)
    at getStream (webpack-internal:///(middleware)/./node_modules/pg/lib/stream.js:8:12)
    at new Connection (webpack-internal:///(middleware)/./node_modules/pg/lib/connection.js:19:36)
    at new Client (webpack-internal:///(middleware)/./node_modules/pg/lib/client.js:48:7)
    at handler (webpack-internal:///(middleware)/./src/pages/api/hello.ts:13:16)
    at eval (webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/api-utils/index.js:32:16)
    at eval (webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/lib/trace/tracer.js:115:36)
    at NoopContextManager.with (webpack-internal:///(middleware)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:2:7062)
    at ContextAPI.with (webpack-internal:///(middleware)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:2:518)
    at NoopTracer.startActiveSpan (webpack-internal:///(middleware)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:2:18108)
 ✓ Compiled in 107ms (263 modules)

@janpio here’s the reproduction repo deployed directly to cloudflare via @cloudflare/next-on-pages

… it works(!) - connecting to a Neon database using node-postgres:

The (currently super ugly…) patches to pg I mentioned above are what fixes https://github.com/cloudflare/next-on-pages/issues/605

🎉

Sorry for the incorrect/misleading post previously!

absolutely no problem! I’ll continue to noodle on this…might take a bit of time to do a similar retrofit that the CF stuff did. I’m also about to go out of town for a bit so…hang tight - i’ll get there eventually!

This patch fixes for me. Specifically: prevents the error Error: The edge runtime does not support Node.js 'crypto' module. when using pg under the Next.js Edge runtime locally.

pg+8.11.5.patch:

diff --git a/node_modules/pg/lib/crypto/utils-webcrypto.js b/node_modules/pg/lib/crypto/utils-webcrypto.js
index 0433f01..588066e 100644
--- a/node_modules/pg/lib/crypto/utils-webcrypto.js
+++ b/node_modules/pg/lib/crypto/utils-webcrypto.js
@@ -13,7 +13,10 @@ module.exports = {
  * The Web Crypto API - grabbed from the Node.js library or the global
  * @type Crypto
  */
-const webCrypto = nodeCrypto.webcrypto || globalThis.crypto
+
+// PATCH: Don't break under Next.js Edge runtime production build
+const webCrypto = ("webcrypto" in nodeCrypto ? nodeCrypto.webcrypto : undefined) ?? globalThis.crypto
+
 /**
  * The SubtleCrypto API for low level crypto operations.
  * @type SubtleCrypto

(I opted to use runtime-agnostic Feature Detection for webcrypto on the crypto import rather than try detect the Next.js Edge runtime specifically via typeof EdgeRuntime === "string", which I assume could be a valid alternative - haven’t verified)

ugg…reading up on the edge runtime vm trying to come up w/ a way to write some test for this within the repo. A bit complicated. Definitely open to ideas & help on this or a PR w/ the patch (though yeah I looked at it, it needs a bit more massaging). Thanks for the work so far @andyjy!

Do I understand correctly that you seem a way to make pg work on Cloudflare Pages via next-on-pages via some changes

Exactly! And specifically those changes are:

  1. Patch pg to compile/bundle successfully under Next.js’ Webpack config. This requires a bunch of patching… and additional next.config.js config.

I believe this fixes https://github.com/cloudflare/next-on-pages/issues/605

(The patches linked above are still a bit of a messy proof-of-concept - in particular there are some “unhappy paths” in pg that execute during handling of e.g. connection errors/exceptions that use other unsupported Node APIs e.g. process.nextTick(), that I believe will crash currently, but could probably(?) be switched out for the cross-platform queueMicrotask()(?).

The changes in my patches would also need a bit more love before they can be merged into pg in a clean way and without breaking anything for non-Edge runtimes and non-Next.js bundler configs. Should be very doable but I expect quite a chore unfortunately…)

Re: Vercel:

But deploying to Vercel is still completely out of the picture, correct

Yes - at least, I observe that when pushing bundled code to Vercel that includes require("cloudflare:sockets"), Vercel’s deployment process objects with error The Edge Function "...." is referencing unsupported modules: cloudflare:sockets

(It’s the same error if I push any code referencing e.g. require("this_module_does_not_exist"))

As I understand it - Vercel’s Edge runtime product specifically supports their Edge Runtime API that is designed to be runnable under various V8-powered environments - AFAIK they don’t particualrly publicise the fact it’s Cloudflare Workers under the hood (and could host their Vercel Edge functions elsewhere under non-Cloudflare at any time - for all I know they may do already!).

So at this point while it may be worth asking a friendly contact at Vercel about the possibility of bypassing the unsupported module: cloudflare:sockets error and running this code on Vercel, even if there is some way to make it work today I still wouldn’t be too optimistic about it not breaking in future. The only practical way I can imagine would be if Vercel add support for a TCP socket library to their official Edge Runtime spec.

Ok wow, that is pretty wild @andyjy - amazing!

Do I understand correctly that you seem a way to make pg work on Cloudflare Pages via next-on-pages via some changes? But deploying to Vercel is still completely out of the picture, correct?

@brianc here you go - reproduction for pages router: https://github.com/andyjy/mre-pg-nextjs-edge

update: I tried a different next-js app using the app router instead of the old pages/* approach

I just did same steps as above except said “yes” when the setup asked me to use an app router.

Setup looks like this:

image

my route.ts file:

import * as pg from 'pg'

export const runtime = 'edge'
const pool = new pg.Pool()

export async function GET() {
  const { rows } = await pool.query('SELECT 1 as one')

  return Response.json({ rows })
}

Immediately when I run ‘yarn next dev’ to start the project it errors out with being unable to import pg-native which is annoying…I’ve never messed w/ the edge runtime before - it’s quite a bit different…so any thoughts on this?


Import trace for requested module:
./node_modules/pg/lib/connection-parameters.js
./node_modules/pg/lib/client.js
./node_modules/pg/lib/index.js
./src/app/api/route.ts
./node_modules/next/dist/build/webpack/loaders/next-edge-app-route-loader/index.js?absolutePagePath=%2FUsers%2Fbmc%2Fsrc%2Fpg-edge-test%2Fsrc%2Fapp%2Fapi%2Froute.ts&page=%2Fapi%2Froute&appDirLoader=bmV4dC1hcHAtbG9hZGVyP25hbWU9YXBwJTJGYXBpJTJGcm91dGUmcGFnZT0lMkZhcGklMkZyb3V0ZSZhcHBQYXRocz0mcGFnZVBhdGg9cHJpdmF0ZS1uZXh0LWFwcC1kaXIlMkZhcGklMkZyb3V0ZS50cyZhcHBEaXI9JTJGVXNlcnMlMkZibWMlMkZzcmMlMkZwZy1lZGdlLXRlc3QlMkZzcmMlMkZhcHAmcGFnZUV4dGVuc2lvbnM9dHN4JnBhZ2VFeHRlbnNpb25zPXRzJnBhZ2VFeHRlbnNpb25zPWpzeCZwYWdlRXh0ZW5zaW9ucz1qcyZyb290RGlyPSUyRlVzZXJzJTJGYm1jJTJGc3JjJTJGcGctZWRnZS10ZXN0JmlzRGV2PXRydWUmdHNjb25maWdQYXRoPXRzY29uZmlnLmpzb24mYmFzZVBhdGg9JmFzc2V0UHJlZml4PSZuZXh0Q29uZmlnT3V0cHV0PSZwcmVmZXJyZWRSZWdpb249Jm1pZGRsZXdhcmVDb25maWc9ZTMwJTNEIQ%3D%3D&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!
 ○ Compiling /api ...
 ⚠ ./node_modules/pg/lib/native/client.js
Module not found: Can't resolve 'pg-native' in '/Users/bmc/src/pg-edge-test/node_modules/pg/lib/native'

I know its trying to webpack the server…which is fun.

Quick note from @prisma that this affects some of our users and is being reported to us: https://github.com/prisma/prisma/issues/24430

(This issue has a reproduction, but that includes Prisma, Next.js and next-auth - that is probably a bit more than what you are asking for @brianc. I am pretty sure just trying to use pg in a Next.js middleware should have the same result though.)

We would love to see this fixed and released, so that Prisma users wanting to use pg in Next.js projects with middleware can do so. Let us know if we can help in any way.