0% found this document useful (0 votes)
8 views

Javascript?

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Javascript?

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

JavaScript tips

How to Manage
Cookies in
JavaScript
Quick & Easy Guide for Beginners!

Slim toumi
Slim toumi
JavaScript tips

What is cookies ?
Cookies are small pieces of data stored in a user's browser to
remember information, like login status or preferences, between
visits. Here’s a guide to working with cookies in JavaScript!

Why Use cookies ?


Persist data: Keep data like user preferences or session info
across page loads
Track activity: Understand user behavior to enhance
experience.
Remember sessions: Enable users to stay logged in.

Creating cookies

Note:
Sets a cookie with a key of username and a value of JohnDoe.
Default expires when the session ends (when the browser is closed).

Slim toumi
Slim toumi
JavaScript tips

Setting a Cookie with Expiration


Cookies can have expiration times using either the expires attribute
(a fixed date) or max-age (duration in seconds).

1. expires: Sets a specific expiration date for the cookie.

Note:
The expires attribute takes a date in UTC string format.

2. max-age: Sets the expiration time relative to when it’s set


(in seconds).

Note:
Expires in 7 days (604800 seconds)
If neither expires nor max-age is set, the cookie will be a session cookie
and will be deleted when the browser is closed.

Slim toumi
Slim toumi
JavaScript tips

Attributes for Cookies


1. path: Defines the scope of the cookie (i.e., the paths where
it’s accessible)..

Note:
path=/: Makes the cookie accessible on all pages of the website.

2. domain: Specifies the domain for which the cookie is valid.


This helps control cross-subdomain access.

3. secure: Ensures the cookie is only sent over HTTPS.

4. httpOnly: Makes the cookie inaccessible to JavaScript


(document.cookie), enhancing security.
Note:
This attribute is set from the server side, not in JavaScript.

Slim toumi
Slim toumi
JavaScript tips

Reading Cookies
To read cookies, access document.cookie, which returns a
string of all cookies in key-value pairs.

Parsing Cookies: To get a specific cookie value, split


document.cookie as follows:

Usage:

Slim toumi
Slim toumi
JavaScript tips

Deleting Cookies
To delete a cookie, set its expiration date to a past date.

Best Practices
Limit usage: Keep cookies small to reduce load time.
Secure data: Only store non-sensitive data, and use
HTTPOnly and Secure attributes when possible.

Use alternatives when possible: For complex data, consider


localStorage or sessionStorage.

Slim toumi
Slim toumi
JavaScript tips

Hopefully You Found It


Usefull!
Be sure to save this post so you
can come back to it later

like Comment Share

Slim toumi
Slim toumi

You might also like