Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[New] async-server-action: Add rule to require that server actions be async #3729

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3,387 changes: 1,948 additions & 1,439 deletions CHANGELOG.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions README.md
Expand Up @@ -293,6 +293,7 @@ module.exports = [

| Name                                  | Description | 💼 | 🚫 | 🔧 | 💡 | ❌ |
| :------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | :- | :- | :- | :- | :- |
| [async-server-action](docs/rules/async-server-action.md) | Require functions with the `use server` directive to be async | ☑️ | | 🔧 | | |
| [boolean-prop-naming](docs/rules/boolean-prop-naming.md) | Enforces consistent naming for boolean props | | | | | |
| [button-has-type](docs/rules/button-has-type.md) | Disallow usage of `button` elements without an explicit `type` attribute | | | | | |
| [checked-requires-onchange-or-readonly](docs/rules/checked-requires-onchange-or-readonly.md) | Enforce using `onChange` or `readonly` attribute when `checked` is used | | | | | |
Expand Down
1 change: 1 addition & 0 deletions configs/recommended.js
Expand Up @@ -5,6 +5,7 @@ const all = require('./all');
module.exports = Object.assign({}, all, {
languageOptions: all.languageOptions,
rules: {
'react/async-server-action': 2,
ljharb marked this conversation as resolved.
Show resolved Hide resolved
'react/display-name': 2,
'react/jsx-key': 2,
'react/jsx-no-comment-textnodes': 2,
Expand Down
57 changes: 57 additions & 0 deletions docs/rules/async-server-action.md
@@ -0,0 +1,57 @@
# Require functions with the `use server` directive to be async (`react/async-server-action`)

💼 This rule is enabled in the ☑️ `recommended` [config](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs).

🔧 This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix).

<!-- end auto-generated rule header -->

Require Server Actions (functions with the `use server` directive) to be async, as mandated by the `use server` [spec](https://react.dev/reference/react/use-server).
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this actually released yet?

despite vercel's usage of it prior to it being fully released, i don't think we should ship a rule until that's the case.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So the feature is still in canary. I understand not wanting to ship a rule for a canary feature, and if that's the final policy then I'm happy to wait until it's out of canary to merge this in.

That being said, Server Components are definitely seeing widespread use, mainly through Vercel, with less stable implementations elsewhere. Additionally, the React team confirmed that they're officially shipping the feature with React 19 (when that comes out is anyone's guess).

Because of this, I think adding this rule (as an optional rule outside of the recommended config) would be very helpful to users using server components, while not impacting users who are not yet using them.


This must be the case even if the function does not use `await` or `return` a promise.

## Rule Details

Examples of **incorrect** code for this rule:

```jsx
<form
action={() => {
'use server';
...
}}
>
...
</form>
```

```jsx
function action() {
'use server';
...
}
```

Examples of **correct** code for this rule:

```jsx
<form
action={async () => {
'use server';
...
}}
>
...
</form>
```

```jsx
async function action() {
'use server';
...
}
```

## When Not To Use It

If you are not using React Server Components.
85 changes: 85 additions & 0 deletions lib/rules/async-server-action.js
@@ -0,0 +1,85 @@
/**
* @fileoverview Require functions with the `use server` directive to be async
* @author Jorge Zreik
*/

'use strict';

const docsUrl = require('../util/docsUrl');
const report = require('../util/report');

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

const messages = {
asyncServerAction: 'Your server action should be async',
};

/**
* Detects a `use server` directive in a given AST node
* @param {ASTNode} node The node to search.
* @returns {boolean} Whether the node given has a `use server` directive.
*/
function hasUseServerDirective(node) {
if (node.body.type !== 'BlockStatement') return false;

const functionBody = node.body.body;
if (functionBody.length === 0) return false;

const potentialDirectiveStatement = functionBody[0];
if (potentialDirectiveStatement.type !== 'ExpressionStatement') return false;

const potentialDirectiveExpression = potentialDirectiveStatement.expression;
if (potentialDirectiveExpression.type !== 'Literal') return false;

return potentialDirectiveExpression.value === 'use server';
jorgezreik marked this conversation as resolved.
Show resolved Hide resolved
}

module.exports = {
meta: {
docs: {
description:
'Require functions with the `use server` directive to be async',
jorgezreik marked this conversation as resolved.
Show resolved Hide resolved
category: 'Possible Errors',
recommended: true,
url: docsUrl('async-server-action'),
},

messages,

fixable: 'code',

schema: [],
},

create(context) {
/**
* Validates that given AST node is async if it has the `use server` directive
* @param {ASTNode} node The node to search.
* @returns {void}
*/
function validate(node) {
if (hasUseServerDirective(node) && !node.async) {
report(context, messages.asyncServerAction, 'asyncServerAction', {
node,
fix(fixer) {
return fixer.insertTextBefore(node, 'async ');
},
});
}
}

return {
FunctionDeclaration(node) {
validate(node);
},
FunctionExpression(node) {
validate(node);
},
ArrowFunctionExpression(node) {
validate(node);
},
};
},
};
1 change: 1 addition & 0 deletions lib/rules/index.js
Expand Up @@ -4,6 +4,7 @@

/** @type {Record<string, import('eslint').Rule.RuleModule>} */
module.exports = {
'async-server-action': require('./async-server-action'),
'boolean-prop-naming': require('./boolean-prop-naming'),
'button-has-type': require('./button-has-type'),
'checked-requires-onchange-or-readonly': require('./checked-requires-onchange-or-readonly'),
Expand Down