Cookies & CORS
Cookies and CORS solve different problems, but both exist for the same reason: your API is usually talked to by a browser, and browsers enforce their own rules about what they will and won't do on your behalf.
Cookies
Reading cookies a browser already sent requires no setup, the Cookie header is parsed automatically on every request:
@Get('/')
async index(@Request req: HttpRequest) {
const theme = req.cookies['theme'] ?? 'light';
// ...
}
Setting one is more hands-on than cookie-parser's res.cookie(), there's no convenience method, you write Set-Cookie directly. Use res.appendHeader(), not res.setHeader(), so you don't clobber a cookie something else on the response already set, such as the session cookie from Sessions:
res.appendHeader('Set-Cookie', 'theme=dark; Path=/; Max-Age=31536000');
setHeader() replaces any existing value for a header, appendHeader() adds to it, and each call ends up as its own Set-Cookie line on the wire, on both engines. Reach for setHeader() when you mean to replace a value, appendHeader() any time you're adding a cookie to a response that might already have one.
CORS
conf.defaults({
cors: {
origins: ['https://my-app.example.com'],
},
});
| Configuration | What happens |
|---|---|
cors.origins left unset, or the request's origin isn't in the list | Any origin may read the response (Access-Control-Allow-Origin: *), but without credentials |
cors.origins is set and includes the request's origin | That origin is allowed, and credentials (cookies, Authorization headers) are permitted too |
That's the whole configuration surface, there's no separate list of allowed methods or headers to maintain. RapidREST always allows a fixed set (GET, HEAD, OPTIONS, PUT, POST, DELETE, and the common request headers) and answers preflight OPTIONS requests directly, before your route code ever runs. The unset-vs-set behavior above is deliberate: wide open with no credentials is a reasonable default for a public API, explicit origins only is the right default the moment cookies or sessions are involved, since those carry credentials.
One thing worth knowing: the key is origins, plural. cors.origin (singular) is silently ignored.
Extra headers on every response
Separately from CORS, add any header to every response your server sends:
conf.defaults({
headers: {
'x-powered-by': 'RapidREST', // the default value
},
});