# cors

Rule `sonarjs/cors`. Cross-Origin Resource Sharing (CORS) policy should be restricted to trusted origins

- Source: sonarjs
- Technologies: JavaScript
- Kind: correctness
- Needs type information: no
- Autofix: no
- Reach: 6.2M weekly downloads of presets that enable it
- Trend: +62.1% last quarter
- Rank: #1199 by reach, #500 by growth

## Linters

| Linter | Rule name | Recommended | Autofix | Details | Docs |
| --- | --- | --- | --- | --- | --- |
| ESLint | `sonarjs/cors` | yes | no | package `eslint-plugin-sonarjs` | [docs](https://rules.sonarsource.com/javascript/RSPEC-5122/) |

## Code examples

### Correct: the rule accepts this

```js
const http = require('http');
const srv = http.createServer((req, res) => {
  res.writeHead(200, { 'Access-Control-Allow-Origin': 'trustedwebsite.com' }); // Compliant
  res.end('ok');
});
srv.listen(3000);
```

```js
const cors = require('cors');

let corsOptions = {
  origin: 'trustedwebsite.com' // Compliant
};

let app = express();
app.use(cors(corsOptions));
```

```js
function (req, res) {
  const origin = req.header('Origin');

  if (trustedOrigins.indexOf(origin) >= 0) {
    res.setHeader('Access-Control-Allow-Origin', origin);
  }
};
```

Examples from the ESLint documentation.

## Enable it

### ESLint: `eslint.config.js`

```js
export default [
  {
    rules: {
      "sonarjs/cors": "error",
    },
  },
];
```

## Presets that enable it

| Preset | Linter | Package | Rules | Weekly downloads | Trend |
| --- | --- | --- | --- | --- | --- |
| [SonarJS recommended](https://lintradar.dev/presets/sonarjs-recommended.md) | ESLint | `eslint-plugin-sonarjs` | 230 | 6.2M | +62.1% |

## Related rules

- [sonarjs/cookie-no-httponly](https://lintradar.dev/rules/sonarjs/cookie-no-httponly.md): Cookies should have the "HttpOnly" flag
- [sonarjs/csrf](https://lintradar.dev/rules/sonarjs/csrf.md): CSRF protections should not be disabled
- [sonarjs/content-security-policy](https://lintradar.dev/rules/sonarjs/content-security-policy.md): Content security policy fetch directives should not be disabled
- [sonarjs/deprecation](https://lintradar.dev/rules/sonarjs/deprecation.md): Deprecated APIs should not be used
- [sonarjs/content-length](https://lintradar.dev/rules/sonarjs/content-length.md): HTTP request content length should be limited
- [sonarjs/different-types-comparison](https://lintradar.dev/rules/sonarjs/different-types-comparison.md): Strict equality operators should not be used with dissimilar types

---

Web page: https://lintradar.dev/rules/sonarjs/cors. Data from npm and the linters' documentation, collected Dec 4, 2026. Site guide for agents: https://lintradar.dev/llms.txt
