How it works...

Our Express app can read and write cookies using the cookie-parser middleware. This module adds new cookie features to both the response and request objects in our Express routes. By reading from these values, we can determine behaviors of our web server, such as writing a new session if it doesn't exist yet.

By signing our cookies, we use the secret key we configured in our /app.js cookie-parser configuration. Needless to say, this key should be considered secret and should not be checked into the source control for the purpose of keeping your application's cookies protected from forgery. Ultimately, session-based security, such as this secret key, is only as good as your own vigilance and encryption strength. A much safer way to handle this key is to use Node's built-in environment variables:

app.use(cookieParser(process.env.cookieSecret));

Alternatively, you can look into using an environment configuration file, such as dotenv. For more information, you can go to https://github.com/motdotla/dotenv.

Signed cookies are a simple hash of the cookie's content and your secret key. If either of the value of the cookie or appended hash is changed, Express will consider the cookie invalid and resolve it with the false value.

Enabling signing on cookies is actually only one of many optional parameters that can be provided when writing a cookie:

Property Type Description
domain String Domain name for the cookie that defaults to the domain name of the app
encode Function A synchronous function used for cookie value encoding that defaults to encodeURIComponent
expires Date The expiry date of the cookie in GMT; if not specified or set to 0, creates a session cookie
httpOnly Boolean Flags the cookie to be accessible only by the web server
maxAge Number Convenient option for setting the expiry time relative to the current time in milliseconds
path String Path for the cookie; defaults to “/”
secure Boolean Marks the cookie to be used with HTTPS only
signed Boolean Indicates whether the cookie should be signed
sameSite Boolean or String Value of the SameSite Set-Cookie attribute
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.251.217