Skip to Content

Security middlewares

CORS, security headers, CSRF protection and rate limiting.

@sukujs/security is a set of middlewares that most public-facing apps need. Each one is a function that returns a middleware, with safe defaults.

bun add @sukujs/security
import sukuSecurity from '@sukujs/security';

const app = await Suku.create({
  features: [UsersFeature],
  middlewares: [
    sukuSecurity.securityHeaders(),
    sukuSecurity.cors({ origin: ['https://app.example.com'], credentials: true }),
    sukuSecurity.rateLimit({ limit: 300, window: '1m' }),
  ],
});

Each function is also a named export: import { cors, rateLimit } from '@sukujs/security'.

MiddlewareProtects againstYou need it when
corsOther websites reading your API's responsesA browser app on another origin calls your API
securityHeadersClickjacking, content sniffing, protocol downgradeAlways
csrfOther websites making requests as a logged-in userYou authenticate with cookies
rateLimitPassword guessing, scraping, abuseAlways, at least on login routes

Order

App-level middlewares run in the order listed, outermost first. Put the ones that decorate every response first, so they also cover responses produced by the ones after them.

middlewares: [securityHeaders(), cors(options), rateLimit(options), csrf()];

With that order a 429 from the rate limiter and a 403 from CSRF protection still carry CORS and security headers, so a browser app can read the error instead of reporting a network failure.

Because errors are turned into responses before they travel back through outer middlewares, the same holds for a 401 thrown by your own authentication middleware.

What this package does not do

Authentication, input validation, account lockout, bot detection and a web application firewall are separate concerns. For tokens and passwords see @sukujs/crypto; for input see validation.

Like the rest of Suku, this package has not had an independent security audit.

On this page