Skip to content

Commit

Permalink
createhash: only call module.require if it exists (#466)
Browse files Browse the repository at this point in the history
Apparently Next.JS "Turbopack" runs code in a weird semi-Node
environment that doesn't have module.require. We don't want to call
require directly because that makes other bundlers put in polyfills. So
make Turbopack use sha.js instead of just throwing. Non-ideal
but better than what we have today.

For apollographql/apollo-server#8004

Co-authored-by: Trevor Scheer <trevor.scheer@gmail.com>
  • Loading branch information
glasser and trevor-scheer committed Jan 2, 2025
1 parent 5534029 commit ea69737
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/early-boxes-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@apollo/utils.createhash": patch
---

Compatibility with Next.js Turbopack
8 changes: 7 additions & 1 deletion packages/createHash/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { isNodeLike } from "@apollo/utils.isnodelike";

export function createHash(kind: string): import("crypto").Hash {
if (isNodeLike) {
// Some Node-like environments (like next.js Turbopack) apparently
// don't have module.require, so double-check before we call it.
// (But don't change the value of isNodeLike because other logic depends on it,
// like Apollo Server signal handling defaults.) This does mean that
// Turbopack will call sha.js instead of the native crypto module, but
// it sure beats throwing because module.require does not exist.
if (isNodeLike && module.require) {
// Use module.require instead of just require to avoid bundling whatever
// crypto polyfills a non-Node bundler might fall back to.
return module.require("crypto").createHash(kind);
Expand Down

0 comments on commit ea69737

Please sign in to comment.