services
Get a key

library / Integrations / I0062

NestJS CommonJS RPC module

A NestJS app that compiles to CommonJS gets a working Carbium RPC client as an injected provider. An async factory loads the package with a dynamic import once at boot, and a service reads the slot, version and health from it.

By Carbium · Web frameworks · I0062 · updated 2026-11-22

01

What the error means

These errors share one cause: code compiled to CommonJS reaches a package that ships as an ES module. TypeScript reports TS1479 when a CommonJS file imports an ES module, because the require call it would emit cannot load that file. TS2307 Cannot find module appears when the resolver never reads the package's exports map. At run time Node reports ERR_REQUIRE_ESM for the same collision, or ERR_PACKAGE_PATH_NOT_EXPORTED when the requested path is not exported.

Recent Node releases can require an ES module that has no top-level await, so whether the run-time half of the error fires depends on your Node version and on the package. The compile-time half depends on your tsconfig.json. @solana/kit 8.6.0 ships both formats: its package.json sets "type": "commonjs", main points at ./dist/index.node.cjs, and exports carries a require entry, so a static import of it compiles and loads in a CommonJS build. The error comes from a package that ships only as an ES module. Open that package's package.json in node_modules and check type, exports and main before choosing a fix, and check again after any version bump.

NestJS makes the error common because Nest CLI projects emit CommonJS. Older ones set module: commonjs in tsconfig.json and have no type field in package.json, while recent starters may set module: nodenext and still emit CommonJS, so check your own tsconfig.json. Every file you write becomes require calls, and every Nest decorator pattern in the documentation assumes that.

02

The module settings that matter

Three settings decide what the compiler emits and what it will resolve. The table lists the combinations a Nest project meets.

SettingWhat it doesEffect here
module: commonjs with moduleResolution: nodeResolves by main and types and ignores exports. Every import becomes require.A package that publishes types only through exports reports TS2307. A static import fails at run time if the package is an ES module.
module: commonjs with await import(...)The compiler rewrites the dynamic import into a require call wrapped in a promise.Looks like a fix and fails the same way. The rewrite is the usual reason the error survives a change to dynamic import.
module: node16 or nodenext with the matching resolutionReads exports and decides per file whether it is CommonJS or ES. A static import in a CommonJS file is still a require; a dynamic import() stays a real import.The static import reports TS1479 for a package that ships only as an ES module. The dynamic import compiles and loads.
"type": "module" in package.jsonEvery .js file becomes an ES module.Fixes the package question and breaks Nest tooling that expects CommonJS, including its default test runner.

With tsc, the factory below needs module and moduleResolution set to nodenext. Plain commonjs works only behind a bundler that keeps import() as an import(). Check the emitted dist file for the word import( before you trust a build.

03

The async provider and its token

Nest resolves a provider whose useFactory returns a promise before the application finishes starting, so every consumer receives the resolved client and never a promise. That fits the problem: the one place that must load the ES module is the factory, and the rest of the app stays CommonJS and unchanged.

The client needs an injection token, because it is a plain object with no class to hang a decorator on. A Symbol works. The provider object has provide for the token and useFactory for the loader. The file below exports both. Its last lines call useFactory directly and read three methods, so you can run the file outside Nest first. Before you put it in a Nest module, delete everything from const started down, because a CommonJS output file rejects top-level await (TS1309).

main.ts
// I0062 · NestJS CommonJS RPC module// https://carbium.sh/library/integrate/nestjs-commonjs-rpc-module// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// An async provider: Nest awaits useFactory once at boot, then injects the finished client.export const CARBIUM_RPC = Symbol("CARBIUM_RPC");// Dynamic import keeps an ES module package out of a CommonJS require() call.export async function rpcFactory(apiKey: string) {  const { createDefaultRpcTransport, createSolanaRpcFromTransport } = await import("@solana/kit");  return createSolanaRpcFromTransport(    createDefaultRpcTransport({      url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",      headers: { "x-api-key": apiKey },    }),  );}// What a Nest module lists under `providers`.export const rpcProvider = {  provide: CARBIUM_RPC,  useFactory: async () => {    const key = process.env.CARBIUM_KEY;    if (!key) throw new Error("Set CARBIUM_KEY.");    return rpcFactory(key);  },};// Run it outside Nest first: load once, then read three cheap methods.// Delete everything from `const started` down before the file goes into a Nest module.const started = performance.now();const rpc = await rpcProvider.useFactory().catch((e: unknown) => {  console.error(e instanceof Error ? e.message : e);  return process.exit(1);});const loadMs = Math.round(performance.now() - started);// getSlot only: commitment left out, kit 8.6.0 sends confirmedconst names = ["getSlot", "getVersion", "getHealth"];const results = await Promise.allSettled([  rpc.getSlot().send(),  rpc.getVersion().send(),  rpc.getHealth().send(),]);results.forEach((r, i) => {  if (r.status === "fulfilled") {    // slots are bigint, which JSON.stringify refuses    console.log(names[i], JSON.stringify(r.value, (_k, v) => (typeof v === "bigint" ? v.toString() : v)));  } else {    console.log(names[i], "failed:", r.reason instanceof Error ? r.reason.message : String(r.reason));  }});console.log(`client loaded in ${loadMs} ms`);

run: node main.ts

The factory calls import("@solana/kit") inside the function body and builds the client from createDefaultRpcTransport. The RPC endpoint is https://services.carbium.sh, replaced by CARBIUM_RPC_URL when that variable is set, and the key travels in the x-api-key header. The key is read from CARBIUM_KEY and never printed.

The three calls leave commitment out. Only getSlot takes a commitment, and @solana/kit 8.6.0 fills in confirmed for it, so it runs at confirmed commitment; getVersion and getHealth take none. All three are cheap cached reads at 1 cell each on every plan, so running the file costs almost nothing. Each call is settled on its own, so one failure leaves the other two lines printed. The load time is the span for the first dynamic import plus building the client. It is paid once, at boot.

04

A service that uses it

In the Nest module, list rpcProvider under providers and under exports if other modules need the client. A service takes it with @Inject(CARBIUM_RPC) in its constructor. Because the client's type comes from a package the service never imports, declare it as Awaited<ReturnType<typeof rpcFactory>>. That type is read from the factory, so the service file contains no import of @solana/kit at all.

A service method then reads like any other Nest code: return (await this.rpc.getSlot().send()).toString(). The toString() matters. Slots, lamports and other large numbers come back as bigint, and Nest's JSON serializer throws on a bigint, so a controller that returns the raw value fails with Do not know how to serialize a BigInt. Convert at the edge of the service.

A health route is a good first consumer. It calls getHealth and getSlot and returns the pair, which tells a load balancer that the provider resolved and the key is accepted. For a first call from a plain script, see First Solana RPC API call. For a client built once on the server in another framework, see Next.js server component reads.

Tests need one change. A unit test that builds the real provider loads the ES package inside Jest's CommonJS runtime, which needs Node's --experimental-vm-modules flag. Override the token with a stub object in the testing module and the test never loads the package.

05

Where it ends

  • Inside a Nest build, check the emitted JavaScript for import( once before you deploy.
  • @solana/kit 8.6.0 publishes a require export, so a static import of it works and the provider is needed only for a package that ships as an ES module alone.
  • A transpiler or bundler step in front of Nest, such as a webpack or SWC build, has its own dynamic import handling. Check its output the same way.
  • The client reads only. Signing and sending belong in a separate provider and are not covered here.
  • Rate limits apply per account, so every key on the account shares one rate budget. One shared client keeps the call count visible in one place.
06

When it goes wrong

what goes wrongwhat to do
TS1479: The current file is a CommonJS module whose imports will produce require calls.A static import of a package that ships as an ES module sits in a CommonJS file. Remove it from every file except the factory, and load the package there with await import(...). Set module and moduleResolution to nodenext so the compiler keeps the dynamic import.
TS2307: Cannot find module for a package that publishes its types only through exports.The resolver is node and ignores the package's exports. Set moduleResolution to node16 or nodenext with a matching module.
ERR_REQUIRE_ESM at start-up although the code uses import().The compiler rewrote import() into require. Open the emitted file in dist, search for import(, and move to the nodenext pair so the call survives compilation.
TS1309 on the await in the last lines of the file.A CommonJS output file rejects top-level await. Delete everything from const started down before the file goes into a Nest module.
Do not know how to serialize a BigInt from a controller.A slot or balance was returned as a bigint. Call toString() in the service before the value reaches the controller.
A Jest test fails with You need to run with a version of node that supports ES Modules in the VM API.The test loaded the real provider. Replace the CARBIUM_RPC token with a stub in the testing module, or run Jest with --experimental-vm-modules.
07

Questions

Why not switch the whole project to ES modules?

You can, and it removes this class of error. It also changes how Nest tooling, Jest and decorators' metadata behave, so it is a larger migration. The async provider keeps the rest of the app as it is and fits in one file.

Does the dynamic import run on every request?

No. Nest runs the factory once during start-up and holds the result. Later injections receive the same client object.

Can I type the client without importing the package?

Yes. Take the type from the factory with Awaited<ReturnType<typeof rpcFactory>>. The service file then has no import of the package, which keeps the compiler quiet under commonjs.

Where does the key come from in a Nest app?

Read CARBIUM_KEY from the environment inside the factory, or inject Nest's config service into useFactory and read it there. Either way the key stays out of the source and out of logs.