By default, the cookies express-session sets will not work if your server's url isn't the same origin as your front end page where you are making requests from. For example, if you are using Create React App's server on localhost:3000
, and your server is running at localhost:8000
, cookies won't be saved without extra configuration for CORS.
If you can avoid multiple origins, I recommend doing that. A single origin avoids CORS configuration which tends to be troublesome. Most front end build tools (including Create React App) have options to proxy requests to your backend server. Even better are tools which build your front end to files that can be directly served by your backend (such as using Parcel's watch
command).
The CORS configuration will include:
- Setting
SameSite
on your cookie options tonone
. - Enabling CORS headers with
Access-Control-Allow-Origin
set to your front end page origin. (Using*
, which is the default withcors()
does not allow cookies.) - Setting
Access-Control-Allow-Credentials
in your CORS config.
If you are using a proxy in front of your server with express-session, and are using secure
cookie flag (and you should always use this in production), you need to configure Express's proxy trust to respect forwarding headers from the proxy. Because proxy trust is effectively disabling a security feature, you need to ensure that your server is only accessible through this proxy, or you will be vulnerable to man-in-the-middle attacks by other people proxying directly.
- secure. In production, you must always use HTTPS, and always enable the
secure
flag which stops the cookie from working over HTTP. - httpOnly. You must always use this option for session cookies.
httpOnly
tells the browser the cookie should not be read or writable by JavaScript on the web page, which is the only protection from a class of common XSS attack.- Note that not enabling this is effectively similar to using localStorage or sessionStorage, with all the security problems that has.
- SameSite. When you are using a single domain for your pages and server, you should set
SameSite
tolax
orstrict
. If you are using multiple origins, you must set it tonone
. In either case, you must still provide separate CSRF mitigation. Theoretically,lax
orstrict
should provide good CSRF mitigation, but it's better to also have explicit protection.
how can my cookies save in browser chrome if my server and clinet has hosting. how setting session-express?