NewNode 26.14: mockResolvedValue and Friends in node:test →
w3/w3-tutorials

Write custom lint rules in TypeScript with Biome 2.6

Biome 2.6 runs lint rules written in TypeScript. Build a rule that keeps process.env in one file and another that rewrites console.log with a code fix.

Updated Nov 25, 20268 min readIntermediatebiome 2.6.9 · @biomejs/runtime 2.6.9 · node 22.22.3 · typescript 7.0.2

Every codebase has rules that no linter ships. "Only src/config.ts may read process.env." "Use our logger, not console.log." Until now, enforcing these in Biome meant a GritQL pattern or a second linter. Biome 2.6 adds JavaScript plugins: lint rules written in JavaScript or TypeScript that run inside Biome itself.

This tutorial builds two rules:

  1. noProcessEnv reports process.env outside one allowed file, and ignores local variables that happen to be called process.
  2. useLogger reports console.log(...) and offers a fix that rewrites it to logger.info(...).

1. Install Biome and the runtime types

terminal
npm init -y
npm i -D -E @biomejs/[email protected] @biomejs/[email protected]
npx biome --version
text
Version: 2.6.9

@biomejs/runtime gives you defineRule, the query helpers and TypeScript types for every syntax node. The -E flag pins exact versions, which matters while the plugin API can still change in a patch.

Add two source files to lint. src/config.ts is the one place allowed to read the environment:

src/config.ts
export const config = {
  databaseUrl: process.env.DATABASE_URL ?? "postgres://localhost/app",
  port: Number(process.env.PORT ?? 3000),
};

src/server.ts breaks both rules:

src/server.ts
import { config } from "./config";

const port = process.env.PORT;
const { STRIPE_KEY } = process.env;

export function start() {
  console.log(`Listening on ${port ?? config.port} with ${STRIPE_KEY}`);
}

src/jobs.ts reads env from a parameter that happens to be called process. It should pass:

src/jobs.ts
// A job runner that receives its own `process` object.
export function runJob(process: { env: Record<string, string> }) {
  return process.env.QUEUE;
}

2. Find the node you want to match

Biome rules match nodes in a concrete syntax tree (CST). Each node kind has an uppercase name. To see the names for real code, run biome inspect file:

terminal
npx biome inspect file src/server.ts
text
1: [email protected]
  0: [email protected]
    0: [email protected]
      0: [email protected]
        0: [email protected] "process" [] []
    1: [email protected] "." [] []
    2: [email protected]
      0: [email protected] "env" [] []
  1: [email protected] "." [] []
  2: [email protected]
    0: [email protected] "PORT" [] []

The output is trimmed to the process.env.PORT part. process.env is a JS_STATIC_MEMBER_EXPRESSION. Its object is a JS_IDENTIFIER_EXPRESSION holding the name process, and its member is the name env. The Biome playground shows the same tree in the browser.

3. Write the process.env rule

lint/no-process-env.ts
import { ast, defineRule, registerDiagnostic } from "@biomejs/runtime/plugin";

// Files that are allowed to read environment variables.
const ALLOWED = ["/src/config.ts"];

export const noProcessEnv = defineRule({
  query: ast("JS_STATIC_MEMBER_EXPRESSION", { semantic: true }),
  run(node, ctx) {
    if (ALLOWED.some((file) => ctx.filePath.endsWith(file))) return;

    // Match `process.env`, not `foo.env` or `process.argv`.
    if (node.member?.text !== "env") return;
    const object = node.object;
    if (object?.kind !== "JS_IDENTIFIER_EXPRESSION") return;
    const reference = object.name;
    if (reference?.text !== "process") return;

    // Skip a local variable or parameter that happens to be called `process`.
    if (ctx.model.binding(reference)) return;

    registerDiagnostic(
      node,
      "error",
      "Read environment variables in src/config.ts and import them from there.",
    );
  },
});

How it works:

  • query tells Biome which nodes to hand to run. ast(...) selects by node kind, so run is called once per member expression in each file.
  • { semantic: true } makes ctx.model available. This is the semantic model: Biome's map of which name refers to which declaration.
  • ctx.filePath is the absolute path of the file being linted, so the allow list is a suffix check.
  • registerDiagnostic(node, severity, message) reports the problem and highlights node.

Register the plugin in biome.json:

biome.json
{
  "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
  "plugins": ["./lint/no-process-env.ts"]
}

Biome strips the TypeScript types when it loads the file, so there is no build step. Run the linter:

terminal
npx biome lint ./src
text
src/server.ts:3:14 plugin ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  × Read environment variables in src/config.ts and import them from there.

    1 │ import { config } from "./config";
    2 │
  > 3 │ const port = process.env.PORT;
      │              ^^^^^^^^^^^
    4 │ const { STRIPE_KEY } = process.env;
    5 │


src/server.ts:4:24 plugin ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  × Read environment variables in src/config.ts and import them from there.

    3 │ const port = process.env.PORT;
  > 4 │ const { STRIPE_KEY } = process.env;
      │                        ^^^^^^^^^^^
    5 │
    6 │ export function start() {


Checked 3 files in 42ms. No fixes applied.
Found 2 errors.

Both reads in server.ts are reported, including the destructuring one. config.ts passes because it is on the allow list, and jobs.ts passes because of the semantic check. The command exits with code 1, so it fails CI too.

4. Why the semantic check matters

A text search for process.env can't tell server.ts and jobs.ts apart. In jobs.ts, process is a parameter, not the Node.js global. ctx.model.binding(reference) returns the declaration a name points to, and undefined for globals. A binding means the name is local, so the rule skips it.

With the binding line removed, the same command reports three errors, the extra one at src/jobs.ts:3:10. This is the kind of check that is hard to get right with a regex and easy with the semantic model.

5. Add a rule with a code fix

The second rule matches with a GritQL pattern instead of a node kind, and attaches a fix:

lint/use-logger.ts
import {
  createMutation,
  defineRule,
  factory,
  grit,
  registerDiagnostic,
} from "@biomejs/runtime/plugin";

export const useLogger = defineRule({
  query: grit("`console.log($args)`"),
  run(call) {
    if (call.kind !== "JS_CALL_EXPRESSION") return;
    const callee = call.callee;
    if (callee?.kind !== "JS_STATIC_MEMBER_EXPRESSION") return;
    if (callee.object?.kind !== "JS_IDENTIFIER_EXPRESSION") return;

    const consoleToken = callee.object.name?.token("valueToken");
    const logToken = callee.member?.token("valueToken");
    if (!consoleToken || !logToken) return;

    // Rewrite `console.log(...)` to `logger.info(...)`.
    const mutation = createMutation(call);
    mutation.replaceToken(consoleToken, factory.token("IDENT", "logger"));
    mutation.replaceToken(logToken, factory.token("IDENT", "info"));

    registerDiagnostic(callee, "warning", "Use the shared logger instead of console.log.", {
      mutation,
      message: "Replace with logger.info().",
      kind: "unsafe",
    });
  },
});
  • grit(...) takes a GritQL code snippet in backticks. $args matches any arguments, including none. It is handy when the shape spans several nodes and would take many kind checks.
  • createMutation(call) starts a set of edits. Nothing changes until the diagnostic is registered with the fix.
  • factory.token("IDENT", "logger") creates a new identifier token. replaceToken keeps the original whitespace and comments around it.
  • The fix is marked unsafe because logger still has to be imported. Biome applies unsafe fixes only when asked.

Add it to biome.json:

biome.json
{
  "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
  "plugins": ["./lint/no-process-env.ts", "./lint/use-logger.ts"]
}

Run npx biome lint ./src again. The two process.env errors are still there, plus a new warning with a diff:

text
src/server.ts:7:3 plugin  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  ! Use the shared logger instead of console.log.

    6 │ export function start() {
  > 7 │   console.log(`Listening on ${port ?? config.port} with ${STRIPE_KEY}`);
      │   ^^^^^^^^^^^
    8 │ }
    9 │

  i Unsafe fix: Replace with logger.info().

    5 5 │
    6 6 │   export function start() {
    7   │ - ··console.log(`Listening·on·${port·??·config.port}·with·${STRIPE_KEY}`);
      7 │ + ··logger.info(`Listening·on·${port·??·config.port}·with·${STRIPE_KEY}`);
    8 8 │   }
    9 9 │

Apply it:

terminal
npx biome lint --write --unsafe ./src
text
Checked 3 files in 102ms. Fixed 1 file.
Found 2 errors.

Line 7 of server.ts now reads logger.info(...). The process.env errors remain, because that rule has no fix: moving a value into config is a decision for a person.

6. Clean up the code and check the plugins

Move the reads into config and add the logger:

src/config.ts
export const config = {
  databaseUrl: process.env.DATABASE_URL ?? "postgres://localhost/app",
  port: Number(process.env.PORT ?? 3000),
  stripeKey: process.env.STRIPE_KEY,
};
src/logger.ts
export const logger = {
  info: (message: string) => process.stdout.write(`${message}\n`),
};
src/server.ts
import { config } from "./config";
import { logger } from "./logger";

export function start() {
  logger.info(`Listening on ${config.port}`);
}
terminal
npx biome lint ./src
text
Checked 4 files in 13ms. No fixes applied.

To see which plugins a project loads, use the new biome inspect plugins command:

terminal
npx biome inspect plugins
text
  i The configuration enables 2 JavaScript plugins.

  JavaScript plugins

  - lint/no-process-env.ts
  - lint/use-logger.ts

  i Biome doesn't run JavaScript plugins during inspection, so their rule names aren't listed.

The plugin files also type-check with tsc in strict mode, because @biomejs/runtime types each node. After the object?.kind check, TypeScript narrows object to JsIdentifierExpression, so object.name type-checks.

When not to use JavaScript plugins

  • You need stability. The API is a developer preview. Pin @biomejs/biome and @biomejs/runtime to the same exact version and read the changelog before upgrading.
  • A pattern is enough. If the rule is "this snippet is banned" with no extra logic, a plain GritQL plugin needs no JavaScript at all.
  • A built-in rule exists. Check the Biome rule list first. Built-in rules are written in Rust, have docs and get fixes upstream.
  • You are porting many ESLint rules. The plugin model is different from ESLint's AST, so rules have to be rewritten, not copied. Your rule sees every token and comment, plus "bogus" nodes that Biome creates when it parses broken code.

The upside is one tool and one parse. Plugins run on a JavaScript engine embedded in Biome, against the tree Biome already built, and they get the same file path and semantic model as the built-in rules.

Next steps

  • Read the JavaScript plugins guide for node.descendants(), node.walk(), kind sets and the trivia APIs for reading comments.
  • Ship your rules to other repos with a biome-manifest.json package, covered in the Biome 2.6 announcement.
  • Run npx biome lint in CI so the rules fail pull requests, not just local runs.

Related tutorials