Implementing CORS in Node.js Applications

Learn how to configure Cross-Origin Resource Sharing (CORS) in your Node.js applications to enable secure client-server communication.

0 likes
4 views

Rule Content

{
  "title": "Implementing CORS in Node.js Applications",
  "description": "Learn how to configure Cross-Origin Resource Sharing (CORS) in your Node.js applications to enable secure client-server communication.",
  "category": "Node.js Cursor Rules",
  "rules": [
    {
      "id": "nodejs-cors-1",
      "description": "Restrict allowed origins to a specific allowlist to prevent unauthorized cross-origin requests.",
      "recommendation": "Define an array of trusted origins and configure the CORS middleware to allow only these origins.",
      "codeExample": "const allowedOrigins = ['https://example.com', 'https://another-example.com'];\napp.use(cors({\n  origin: function (origin, callback) {\n    if (!origin || allowedOrigins.includes(origin)) {\n      callback(null, true);\n    } else {\n      callback(new Error('Not allowed by CORS'));\n    }\n  }\n}));",
      "references": [
        {
          "title": "Security implications of cross-origin resource sharing (CORS) in Node.js",
          "url": "https://snyk.io/blog/security-implications-cors-node-js/"
        }
      ]
    },
    {
      "id": "nodejs-cors-2",
      "description": "Use secure cookies and tokens for authentication to enhance security in cross-origin requests.",
      "recommendation": "Set the 'credentials' option to true in the CORS configuration and ensure secure handling of authentication tokens.",
      "codeExample": "app.use(cors({\n  origin: 'https://example.com',\n  credentials: true\n}));\napp.use(passport.initialize());\npassport.use(new JwtStrategy(/* ... */));\napp.get('/books', passport.authenticate('jwt', { session: false }), (req, res) => { /* ... */ });",
      "references": [
        {
          "title": "Security implications of cross-origin resource sharing (CORS) in Node.js",
          "url": "https://snyk.io/blog/security-implications-cors-node-js/"
        }
      ]
    },
    {
      "id": "nodejs-cors-3",
      "description": "Limit exposed headers and HTTP methods to minimize the attack surface.",
      "recommendation": "Specify only the necessary headers and HTTP methods in the CORS configuration.",
      "codeExample": "app.use(cors({\n  exposedHeaders: ['Content-Type', 'Authorization'],\n  methods: ['GET', 'POST']\n}));",
      "references": [
        {
          "title": "Security implications of cross-origin resource sharing (CORS) in Node.js",
          "url": "https://snyk.io/blog/security-implications-cors-node-js/"
        }
      ]
    },
    {
      "id": "nodejs-cors-4",
      "description": "Implement security headers outside of CORS to further secure your application.",
      "recommendation": "Use middleware like Helmet to set additional security headers.",
      "codeExample": "const helmet = require('helmet');\napp.use(helmet());\nconst cspConfig = {\n  directives: {\n    defaultSrc: [\"'self'\", 'https://example.com'],\n    // ...other CSP directives matching your app's needs.\n  }\n};\napp.use(helmet.contentSecurityPolicy(cspConfig));",
      "references": [
        {
          "title": "Security implications of cross-origin resource sharing (CORS) in Node.js",
          "url": "https://snyk.io/blog/security-implications-cors-node-js/"
        }
      ]
    },
    {
      "id": "nodejs-cors-5",
      "description": "Handle preflight requests properly to ensure smooth cross-origin communication.",
      "recommendation": "Respond to OPTIONS requests with the appropriate CORS headers.",
      "codeExample": "app.options('*', (req, res) => {\n  res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');\n  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');\n  res.sendStatus(200);\n});",
      "references": [
        {
          "title": "Avoid These Mistakes When Handling CORS",
          "url": "https://corsproxy.io/blog/cors-mistakes/"
        }
      ]
    },
    {
      "id": "nodejs-cors-6",
      "description": "Avoid using wildcards ('*') for 'Access-Control-Allow-Origin' to prevent security risks.",
      "recommendation": "Specify exact origins that are allowed to access your resources.",
      "codeExample": "const allowedOrigins = ['https://example.com', 'https://anotherdomain.com'];\napp.use((req, res, next) => {\n  const origin = req.headers.origin;\n  if (allowedOrigins.includes(origin)) {\n    res.setHeader('Access-Control-Allow-Origin', origin);\n  }\n  next();\n});",
      "references": [
        {
          "title": "Avoid These Mistakes When Handling CORS",
          "url": "https://corsproxy.io/blog/cors-mistakes/"
        }
      ]
    },
    {
      "id": "nodejs-cors-7",
      "description": "Regularly review and update your CORS policy to adapt to evolving security requirements.",
      "recommendation": "Periodically audit your CORS configurations to ensure they meet current security standards.",
      "references": [
        {
          "title": "Avoid These Mistakes When Handling CORS",
          "url": "https://corsproxy.io/blog/cors-mistakes/"
        }
      ]
    }
  ]
}