❯ehsan.blog
~/blog/grep-your-library-before-you-rewrite-it-framework-coupling — zsh
❯cat grep-your-library-before-you-rewrite-it-framework-coupling.md

Grep your library before the framework-free rewrite

·8 min read

Grep your library before the framework-free rewrite — article card for a post by Ehsan Shahid

I have a logging library called nextjs-logger. It does what the name says: it logs things in a Next.js app. For two years I have carried around a quiet assumption about it — that if I ever wanted it to work in Express, or Vue, or a plain HTML page, I would have to rewrite most of it. It is called nextjs-logger. React must be baked in everywhere, right?

Last week I tested that assumption instead of trusting it. I ran one grep over my own library. It took about four seconds.

Out of 36 source files, 3 import React or Next — 8% of the codebase.

That number changed the whole shape of the rewrite ahead of me, and I think the same thing is probably true of your library too. So here is the command, what the answer actually means, and the second grep you need — because the first one lies to you in a specific way that is easy to miss.

The question you are actually asking

“Is my code framework-agnostic?” sounds like a big architectural question. It is not. It is a small, boring, countable question:

Which of my files would stop working if React and Next were not installed?

A file that never mentions React does not care whether React exists. It will run in Node, in a browser, in Bun, in a Cloudflare Worker. The framework is not inside it. The framework is just the building it happens to live in.

So count the files that mention it.

Grep number one: who imports a framework?

Run this from your source folder:

bash
grep -rlE "from ['\"](react|next)(/|['\"])" . --include=*.ts --include=*.tsx | grep -v __tests__

Reading it left to right:

  • -r means look in every folder underneath this one.
  • -l means print the file names, not the matching lines. You want a list of suspects, not a wall of code.
  • -E turns on the fuller pattern syntax so that (react|next) means “either word”.
  • (/|['\"]) is the important bit. It matches react and next/headers, but it will not match a package called react-query or nextra. Without it you get false alarms.
  • The last grep -v __tests__ drops test files. Tests are supposed to import the framework — they are pretending to be an app.

My answer:

plaintext
./provider/LoggerBootstrapClient.tsx
./provider/LoggerProvider.tsx
./provider/useLogger.ts

Three files, all in one folder. Everything else — the log dispatcher, the config, the error serializer, the timers, the schema validation, the rate limiter, the HMAC session tokens, the log sanitiser, the file transport, the HTTP transport, the OTLP transport, the queue that batches logs in the browser — none of it mentions React at any point.

I genuinely did not believe the queue would pass. That file talks to TanStack Pacer, batches logs per level, and flushes them when the tab closes. In my head it was deeply tangled with React. It is not. It listens for visibilitychange on document and beforeunload on window. Those are browser features, not React features. A plain HTML page with a <script> tag has both.

That distinction matters a lot: “needs a browser” and “needs React” are two different dependencies. Code that needs a browser can move to any frontend framework, or to no framework at all. Code that needs React can only move to React.

Grep number two: the coupling that imports nothing

Here is where the first grep quietly lies.

In my library there is a file called relay/server-action.ts. It takes log entries from the browser and writes them out on the server. The import grep says it is clean — it imports nothing from React and nothing from Next.

It is also completely impossible to use outside Next.js.

Line 29 of that file:

ts
'use server';

That string is not a comment. It is a directive: a marker the bundler reads to decide how a file is compiled and where it is allowed to run. 'use server' marks a Next.js Server Action. 'use client' marks a file that must be shipped to the browser. They look like loose strings sitting at the top of a file, so grep for imports walks straight past them. (Bundlers mishandle them too — I lost a day once to a build that silently dropped ‘use client’ from the output.)

Catch both at once:

bash
grep -rlE "from ['\"](react|next)(/|['\"])|^['\"]use (client|server)['\"]" . --include=*.ts --include=*.tsx | grep -v __tests__

The | in the middle means “or”. The ^ means the directive has to start its own line, so a sentence about 'use client' inside a comment does not trip it.

My answer went from three files to five:

plaintext
./provider/client.ts
./provider/LoggerBootstrapClient.tsx
./provider/LoggerProvider.tsx
./provider/useLogger.ts
./relay/server-action.ts

The two new ones import nothing framework-shaped at all. They are coupled by a string. If I had planned my extraction off the first grep only, I would have cheerfully moved both into a “works everywhere” package and found out at build time — or worse, at someone else’s build time.

What grep still cannot see

I want to be straight about the limits, because a check you trust too much is worse than no check.

This finds static import ... from lines. It does not find require('react'), or a lazy await import('next/headers'), or a framework reached through a re-export in another file. Add require\(['\"](react|next) to the pattern if your codebase uses CommonJS.

And it cannot see the subtlest kind of coupling at all: a function whose shape is a framework contract. My relay/route-handler.ts is the test case. It is clean by both greps, and its entry point is:

ts
export async function POST(request: Request) {

Next’s App Router calls a file’s exported POST when a POST request arrives. So that export name is a Next convention. But look at the type: Request. Not NextRequest — the standard web Request that Node 18+, Deno, Bun, Cloudflare Workers and browsers all ship. The body of the function uses nothing Next-specific.

That file is not stuck. Porting it to Express or Hono means renaming the export and wiring it to a route — a few lines of glue, not a rewrite. Compare that to server-action.ts, which cannot exist outside Next at all. Both are “Next files” in the folder sense. Only one is actually trapped.

Grep gives you the list. You still have to open the handful of files it finds and ask which kind each one is.

Why the count changes the plan

Before counting, the job in my head was “rewrite a Next.js logger into a universal one” — a scary, months-long, high-risk project with a real chance of breaking logging for existing users.

After counting, the job is “move 31 files that already don’t care, and write new adapters for the 5 that do.” Moving files that compile and pass their tests is boring work. Boring is the goal. The risky part shrank to five files I can name.

The order follows from that too. I convert to a monorepo first with zero logic changes — same tests, same output — and only then pull the shared code into its own package. Moving-with-no-changes and changing-things are two different kinds of risk, and if you do them in one pass you will not know which one broke the build. (My repo is at that first step now: one packages/nextjs workspace, nothing extracted yet.)

Make the check permanent, or it rots

Here is the thing about a number like “3 of 36”: it is true today and meaningless in six months. One tired evening, one quick fix, one useEffect import added to a shared file because it was the fastest thing available — and the shared package quietly stops being shared. Nobody notices until an Express user opens an issue asking why their build downloads React.

There is a second reason to care, beyond tidiness. The shared files are the ones carrying bug fixes I paid for in production — things like the log injection hole an unescaped newline opened up. If each adapter grows its own near-copy of that sanitising code, I get to rediscover that bug once per framework.

So the grep becomes a test. dependency-cruiser is the standard tool for this: you declare a rule like “nothing in packages/core may resolve an import to react or next” and it fails CI when something does. A rule in a README is a wish. A rule in CI is a rule.

Try it on your own repo

Copy this, run it in your source folder, and see what comes back:

bash
grep -rlE "from ['\"](react|next|vue|svelte)(/|['\"])|^['\"]use (client|server)['\"]" . --include=*.ts --include=*.tsx --include=*.js --include=*.jsx | grep -v __tests__

If the list is long, fine — now you know, and you know exactly which files to start with. If the list is short, you just found out that the rewrite you have been putting off is mostly a git mv.

Either way it beats guessing. I guessed for two years and was wrong by a factor of ten.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.