Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/eslint-plugin-next-initial.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/eslint-plugin-next': minor
---

Add experimental ESLint plugin `@clerk/eslint-plugin-next`, with a single `require-auth-protection` rule for the Next.js App router. This rule helps enforce auth protections are present at the page/route/server function level.
4 changes: 4 additions & 0 deletions .github/labeler.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ elements:
- changed-files:
- any-glob-to-any-file: packages/elements/**

eslint-plugin-next:
- changed-files:
- any-glob-to-any-file: packages/eslint-plugin-next/**

expo:
- changed-files:
- any-glob-to-any-file: packages/expo/**
Expand Down
132 changes: 132 additions & 0 deletions packages/eslint-plugin-next/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<p align="center">
<a href="https://clerk.com?utm_source=github&utm_medium=clerk_eslint_plugin_next" target="_blank" rel="noopener noreferrer">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://images.clerk.com/static/logo-dark-mode-400x400.png">
<img src="https://images.clerk.com/static/logo-light-mode-400x400.png" height="64">
Comment thread
Ephem marked this conversation as resolved.
</picture>
</a>
<br />
</p>

# @clerk/eslint-plugin-next

<div align="center">

[![Chat on Discord](https://img.shields.io/discord/856971667393609759.svg?logo=discord)](https://clerk.com/discord)
[![Clerk documentation](https://img.shields.io/badge/documentation-clerk-green.svg)](https://clerk.com/docs?utm_source=github&utm_medium=clerk_eslint_plugin_next)
[![Follow on X](https://img.shields.io/twitter/follow/clerk?style=social)](https://x.com/intent/follow?screen_name=clerk)

[Changelog](https://github.com/clerk/javascript/blob/main/packages/eslint-plugin-next/CHANGELOG.md)
·
[Report a Bug](https://github.com/clerk/javascript/issues/new?assignees=&labels=needs-triage&projects=&template=BUG_REPORT.yml)
·
[Request a Feature](https://feedback.clerk.com/roadmap)
·
[Get help](https://clerk.com/contact/support?utm_source=github&utm_medium=clerk_eslint_plugin_next)

</div>

## Overview

> [!NOTE]
> This lint rule is experimental, but should already be working well.
>
> We encourage trying it out and getting in touch with us about your experience.

ESLint rules to help with Clerk patterns in the Next.js App Router.

Currently contains a single rule to help enforce protecting resources where they are used. Instead of relying on a proxy matcher, you declare which folders are protected and the `require-auth-protection` rule flags any `page`, `layout`, `template`, `default`, `route`, or Server Action under those folders that doesn't guard itself.

The rule only detects protected or not, which corresponds to signed in/signed out. You are still responsible for making sure the checks are _correct_ and that the user has the correct permissions to access the resource.

> The config **declares intent for tooling — it does not guard anything at runtime.** Protection only happens when each resource calls `await auth.protect()` (or an equivalent check). This rule verifies that it does.

## Installation

```sh
npm install --save-dev @clerk/eslint-plugin-next
```

Requires ESLint `>=9` (flat config).

## Usage

Register the plugin and declare your protected/public folder globs in `eslint.config.mjs`:

```js
import clerkNext from '@clerk/eslint-plugin-next';

export default [
{
plugins: { '@clerk/next': clerkNext },
rules: {
'@clerk/next/require-auth-protection': [
'error',
{
protected: ['app/**'],
public: ['app/sign-in/**', 'app/sign-up/**'],
},
],
},
},
];
```

## Options

| Option | Type | Default | Description |
| ------------------- | --------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `protected` | `string[]` (required) | — | Folder globs whose resources must be guarded. |
| `public` | `string[]` | `[]` | Folder globs that are exempt. |
| `mixedScopeLayouts` | `'auto' \| string[]` | `'auto'` | Layouts/templates that intentionally wrap both protected and public descendants. `'auto'` allows them silently; a list requires each such folder to be acknowledged explicitly. |

Globs use a minimal dialect — only `*` (single segment) and `**` (any depth). When a folder matches both `protected` and `public`, the most specific pattern wins, and `protected` wins ties.

## What counts as protected

The rule is satisfied when the relevant function guards itself at the top, either by calling `auth.protect()`:

```ts
import { auth } from '@clerk/nextjs/server';

export default async function Page() {
await auth.protect();
// ...
}
```

…or by an early-exit check derived from `auth()` that returns, throws, or calls `notFound()` / `redirect()`:

```ts
import { auth } from '@clerk/nextjs/server';

export default async function Page() {
const { userId } = await auth();
if (userId === null) notFound();
// ...
}
```

Recognized checks include `!isAuthenticated`, `isAuthenticated === false`, `userId === null`, and `sessionId === null` (from `auth()` imported as `@clerk/nextjs/server`). Client components (`'use client'`) are skipped.

General protection must happen at the top of the function, but additional narrowing auth checks can happen further down.

## Support

For help, visit our [support page](https://clerk.com/contact/support?utm_source=github&utm_medium=clerk_eslint_plugin_next).

## Contributing

We're open to all community contributions! Please read [our contribution guidelines](https://github.com/clerk/javascript/blob/main/docs/CONTRIBUTING.md) and [code of conduct](https://github.com/clerk/javascript/blob/main/docs/CODE_OF_CONDUCT.md).

## Security

`@clerk/eslint-plugin-next` is a static analysis aid, not a runtime guard. It's provided to help you catch missing protections and it does error on the side of caution, but there are no guarantees there might not be edge cases it fails to detect.

_For more information and to report security issues, please refer to our [security documentation](https://github.com/clerk/javascript/blob/main/docs/SECURITY.md)._

## License

This project is licensed under the **MIT license**.

See [LICENSE](https://github.com/clerk/javascript/blob/main/packages/eslint-plugin-next/LICENSE) for more information.
75 changes: 75 additions & 0 deletions packages/eslint-plugin-next/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{
"name": "@clerk/eslint-plugin-next",
"version": "0.0.0",
"description": "ESLint plugin for enforcing Clerk auth protection in Next.js App Router resources.",
"keywords": [
"auth",
"authentication",
"eslint",
"eslintplugin",
"eslint-plugin",
"next",
"nextjs",
"clerk"
],
"homepage": "https://clerk.com/",
"bugs": {
"url": "https://github.com/clerk/javascript/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/clerk/javascript.git",
"directory": "packages/eslint-plugin-next"
},
"license": "MIT",
"author": "Clerk",
"sideEffects": false,
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"./package.json": "./package.json"
},
"main": "./dist/index.js",
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"clean": "rimraf ./dist",
"dev": "tsup --watch",
"format": "node ../../scripts/format-package.mjs",
"format:check": "node ../../scripts/format-package.mjs --check",
"lint": "eslint src",
"lint:attw": "attw --pack . --profile node16",
"lint:publint": "publint",
"test": "vitest run",
"test:watch": "vitest watch",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@types/node": "^22.19.17",
"@typescript-eslint/parser": "8.58.0",
"@typescript-eslint/utils": "8.58.0",
"eslint": "9.31.0",
"tsup": "catalog:repo",
"typescript": "catalog:repo",
"vitest": "3.2.4"
},
"peerDependencies": {
"eslint": ">=9"
},
"engines": {
"node": ">=20.9.0"
},
"publishConfig": {
"access": "public"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`@clerk/eslint-plugin-next public shape > exposes a stable set of configs 1`] = `[]`;

exports[`@clerk/eslint-plugin-next public shape > exposes a stable set of rules 1`] = `
[
"require-auth-protection",
]
`;
53 changes: 53 additions & 0 deletions packages/eslint-plugin-next/src/__tests__/file-info.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest';

import { getRelativeFolder } from '../lib/file-info.js';

describe('getRelativeFolder', () => {
it('roots at the `app` segment for a root-level App Router', () => {
expect(getRelativeFolder('/proj/app/dashboard/page.tsx', '/proj')).toBe('app/dashboard');
});

it('supports the `src/app` convention (the `src` segment is skipped)', () => {
expect(getRelativeFolder('/proj/src/app/dashboard/page.tsx', '/proj')).toBe('app/dashboard');
});

it('ignores a spurious `app` segment in the absolute prefix when `cwd` is provided', () => {
// Without cwd-relativization, the leading `/Users/app/...` would anchor the
// folder at the wrong `app`. Relativizing against the project root fixes it.
expect(getRelativeFolder('/Users/app/work/myproj/app/dashboard/page.tsx', '/Users/app/work/myproj')).toBe(
'app/dashboard',
);
});

it('roots at the shallowest `app` when an inner route folder is also named `app`', () => {
expect(getRelativeFolder('/proj/app/app/page.tsx', '/proj')).toBe('app/app');
});

it('does not match segments that merely contain `app`', () => {
expect(getRelativeFolder('/proj/myapp/dashboard/page.tsx', '/proj')).toBe('myapp/dashboard');
expect(getRelativeFolder('/proj/app-utils/foo.ts', '/proj')).toBe('app-utils');
});

it('normalizes Windows-style separators', () => {
expect(getRelativeFolder('C:\\proj\\app\\dashboard\\page.tsx', 'C:\\proj')).toBe('app/dashboard');
});

it('falls back to scanning the absolute path when the file is outside `cwd`', () => {
// Mirrors how RuleTester lints in-memory code: the filename is absolute and
// not under the real cwd, so the absolute path is scanned for `app`.
expect(getRelativeFolder('/elsewhere/app/dashboard/page.tsx', '/proj')).toBe('app/dashboard');
});

it('returns the project-relative folder when there is no `app` segment but the file is under cwd', () => {
expect(getRelativeFolder('/proj/utils/foo.ts', '/proj')).toBe('utils');
});

it('returns null when there is no `app` segment and the file is outside cwd', () => {
expect(getRelativeFolder('/elsewhere/utils/foo.ts', '/proj')).toBeNull();
});

it('returns null for an empty filename', () => {
expect(getRelativeFolder(undefined, '/proj')).toBeNull();
expect(getRelativeFolder('', '/proj')).toBeNull();
});
});
Loading
Loading