Writing Custom ESLint Rules with AI Assistance
How to use AI to write, test, and iterate on custom ESLint rules that encode your team's conventions — without memorizing the AST API.
Custom ESLint rules are the right tool for encoding conventions that can’t be expressed through config alone — “never import the database client directly in route files,” “all async helpers in this module must be wrapped in withRetry,” “all API handlers must call requireAuth before accessing request data.” The problem is that writing them from scratch requires knowing the ESTree AST specification well enough to target the right node types and write correct visitor logic. That’s a barrier most teams don’t bother crossing.
AI coding assistants lower that barrier significantly. You don’t need to memorize the AST API — you need to describe the pattern you want to catch and show the AI a few examples. This article covers how to work with an AI to write, test, and ship custom ESLint rules reliably.
What you’re actually building
An ESLint rule is a module that exports a create function. The function receives a context object and returns a visitor — an object whose keys are AST node types and whose values are functions that run when ESLint visits a matching node.
// The skeleton of every ESLint rule
module.exports = {
meta: {
type: "suggestion",
docs: { description: "Enforce a specific pattern" },
schema: [],
},
create(context) {
return {
CallExpression(node) {
// Inspect node, call context.report() to flag a violation
},
};
},
};
The challenge isn’t the structure — it’s knowing which node type to visit and how to navigate that node’s properties to check the condition you care about. The AI is good at exactly that part.
How to prompt for a rule
The most effective pattern is to give the AI three things:
- A clear English description of the pattern to catch
- One or two code examples that should trigger the rule
- One or two code examples that should not trigger it
Write an ESLint rule called "no-direct-db-in-routes" that flags
any direct import of `../lib/db` or `../../lib/db` from inside
files matching the pattern `src/app/api/**/*.ts`.
Should trigger:
// Inside src/app/api/users/route.ts
import { db } from "../../lib/db";
Should NOT trigger:
// Inside src/app/api/users/route.ts
import { getUsers } from "../../lib/queries"; // indirect, fine
// Inside src/lib/queries.ts
import { db } from "../db"; // not in an API route file, fine
The positive and negative examples are what keep the rule from being too broad or too narrow. Without them, the AI produces a rule that catches the right pattern but also fires on a dozen things you didn’t intend — or misses half of them.
Getting the right AST node type
The AI sometimes gets the node type wrong on the first attempt, especially for patterns involving member expressions, chained calls, or optional chaining. When that happens, the fastest fix is to look up the actual AST for your example code and tell the AI what you see.
AST Explorer lets you paste a snippet and inspect the resulting tree. Set the parser to @typescript-eslint/parser for TypeScript projects. Then give the AI the relevant node structure directly:
Here's the AST for `import { db } from "../../lib/db"`:
{
type: "ImportDeclaration",
source: {
type: "Literal",
value: "../../lib/db"
},
specifiers: [...]
}
The rule should visit ImportDeclaration nodes and check
whether source.value ends with "/lib/db" and whether the
current filename (from context.getFilename()) matches src/app/api/.
Describing the structure from the actual tree is faster than describing it in the abstract. The AI produces valid visitor code on the first attempt most of the time when you do this.
Writing the test alongside the rule
ESLint’s RuleTester is straightforward, and generating the test at the same time as the rule is worth doing. The test doubles as documentation — it’s the most precise specification of what the rule catches and doesn’t catch.
Prompt:
Write a RuleTester test suite for the rule above. Include:
- 3 valid cases (should not trigger)
- 3 invalid cases (should trigger), each with the expected
message and the correct error location
Use flat config format with @typescript-eslint/parser.
The resulting test looks like this:
const { RuleTester } = require("eslint");
const rule = require("./no-direct-db-in-routes");
const tester = new RuleTester({
languageOptions: {
parser: require("@typescript-eslint/parser"),
},
});
tester.run("no-direct-db-in-routes", rule, {
valid: [
{
filename: "src/app/api/users/route.ts",
code: `import { getUsers } from "../../lib/queries";`,
},
{
filename: "src/lib/queries.ts",
code: `import { db } from "../db";`,
},
],
invalid: [
{
filename: "src/app/api/users/route.ts",
code: `import { db } from "../../lib/db";`,
errors: [
{
message:
"API routes must not import db directly — use a query function from lib/queries",
},
],
},
],
});
Run the tests before trusting the rule. The AI gets the visitor logic right most of the time but sometimes gets the error location wrong — pointing to the import declaration instead of the source literal, for instance. The RuleTester makes this visible immediately.
The same habit of generating tests alongside the implementation applies here as it does in Writing Tests with AI: tests aren’t a separate step, they’re the spec.
What taught me to test first — Josh: I deployed a custom rule that was supposed to catch missing
awaiton a specific async helper. It passed my manual smoke test but the error location pointed to the wrong token — highlighting the closing parenthesis of the call expression instead of the function name. The ESLint error was completely useless in the editor.RuleTesterwould have caught that in 30 seconds. I lost 20 minutes because I skipped it.
Iterating on false positives
Custom rules almost always have edge cases the first version doesn’t handle. The most reliable way to surface them is to run the rule on your existing codebase before shipping it:
npx eslint --rulesdir src/eslint-rules \
--rule '{"local/no-direct-db-in-routes": "error"}' \
src/
Review the output for false positives — cases where the rule fires but shouldn’t. Take each one back to the AI:
The rule is triggering on this case, which should be allowed:
// src/app/api/health/route.ts
import { db } from "../../lib/db";
// This is the health-check route — it's explicitly permitted
// to ping the DB directly for the connection test.
Add an exception: if context.getFilename() contains /api/health/,
skip the check.
Specific false positives with context produce better fixes than vague descriptions. “It fires on some edge cases” produces a guess. “It fires on health-check routes because they intentionally import db directly” produces a targeted addition to the visitor logic.
This iteration pattern — run against the full codebase, collect false positives, return them to the AI with explanation — usually converges in two or three rounds. It’s the same feedback loop described in Structured Feedback Loops for AI Coding: tight cycles with concrete examples produce stable output faster than trying to anticipate all edge cases up front.
Packaging rules for the team
Once a rule works and its tests pass, putting it in a local plugin makes it available without manual path configuration. The structure is minimal:
src/eslint-rules/
index.js ← plugin entry point
no-direct-db-in-routes.js
no-direct-db-in-routes.test.js
// src/eslint-rules/index.js
module.exports = {
rules: {
"no-direct-db-in-routes": require("./no-direct-db-in-routes"),
},
};
// eslint.config.js
const localRules = require("./src/eslint-rules");
module.exports = [
{
plugins: { local: localRules },
rules: {
"local/no-direct-db-in-routes": "error",
},
},
];
The AI can generate this boilerplate from a one-line prompt once you have a working rule.
What AI is good at here — and what it isn’t
The AI is reliable at:
- Generating visitor logic for well-specified patterns when given concrete AST examples
- Writing
RuleTestertest cases - Iterating on false positives when given specific, contextualized examples
- Generating the plugin wrapper and config boilerplate
It’s less reliable at:
- Rules that require cross-file analysis. ESLint visitors run per-file. If catching the pattern requires knowing what another file exports, ESLint is probably not the right enforcement tool — a custom TypeScript plugin or a build-time check is a better fit.
- Rules with complex scope tracking. The ESLint Scope API is powerful but subtle. Expect iteration and always run the full
RuleTestersuite before shipping. - Autofix implementations. Fixers that modify the AST are more complex than the checker half. Test these aggressively: the AI tends to produce fixers that work on the common case and silently corrupt code in edge cases.
For the last point, ask for the checker and the fixer as separate tasks. When you prompt for them together, the AI tends to give the fixer less attention. When you ask for the fixer in a fresh prompt with the working checker pasted in as context, it treats the fixer as the primary task.
The convention enforcement payoff
A working custom rule turns a code review comment you’ve left on 15 pull requests into a check that runs at lint time, in the editor, before the branch is pushed. The convention gets enforced automatically — before the PR is opened, before the reviewer sees it, before the author has to revise it.
The barrier isn’t knowing the ESLint API anymore. It’s being specific enough about the pattern you’re catching. That’s work you’d be doing in the code review comment anyway — the AI just turns that description into a rule.

