How to use cookies in Flask

Read Time:9 Minute, 10 Second

Table of Contents

We’ll look at Flask cookies and use them in the Flask web application in this tutorial. So strap in, and let’s get this party started.

What exactly are cookies?

Cookies, or more precisely, HTTP cookies, are text files saved on the client machine. Based on the cookie settings in the client browser, each cookie might be stored permanently or for a defined expiry time.

The cookie is automatically erased from the client browser when it reaches its expiration date and time. Client-side cookies keep track of and remember the user’s online activities. This data is then used to improve the user’s overall experience on the site.

How do they work?

HTTP refers to a stateless protocol, which means the server has no way of knowing if a user is visiting the site for the first time or not. Sites utilize cookies to solve this problem.

As a result, when a client sees a site for the first time, the site does not set any cookies on the client. Consequently, the server produces a new cookie and transmits it to the client.


As a result, the client machine will attach the cookie to the request and send it on subsequent visits. The server then obtains the cookies from the request object and utilizes them to improve the user experience on the site.

What is the purpose of cookies?

In a nutshell, cookies improve the user’s experience on the site by storing and tracking the user’s activities. They also save information like the site’s expiration date, route, and domain.

Cookies are used in a variety of settings, including:

  • You may have observed that when you leave an eCommerce or social networking website like Facebook without signing out, your account remains signed in the next time you return.
  • You can get product recommendations based on your browser’s previous search history on many eCommerce websites. All of this is accomplished through the use of cookies.

Cookies in Flask

A cookie is a text file saved on a client’s computer. Its goal is to recall and track information about a client’s usage to improve the visitor experience and site statistics.

A cookie’s attribute is contained in a Request object. It’s a dictionary object that contains all of the cookie variables and their values that a client has sent. A cookie also saves the site’s expiry time, path, and domain name, among other things.


Cookies are stored on the client’s machine by the server. They are associated with the client’s request to that server in all subsequent transactions until the cookie’s lifetime expires, or the server’s specific web page erases it.

The cookies are associated with the Request object in the Flask as a dictionary object that contains all of the cookie variables and their values sent by the client. Flask makes setting the website’s expiry time, path, and domain name easy.

Create cookie

Cookies are set on the response object in Flask. To get a response object from a view function’s return value, use the make_response() function. Then, to store a cookie, utilize the response object’s set_cookie() function.

It’s simple to read a cookie backward. The request.cookies method get() helps to read a cookie. A simple form appears when you access the ‘/’ URL in the following Flask application.

The HTML page below has a single text input.


Setting the cookie

The set_cookie() method in Flask is used to set cookies on the response object. The view function’s make_response() process creates the response object.

The form submission is directed to the URL ‘/code/set/cookie’. The linked view function creates a userID cookie and renders a new page.

The cookie has been set if you open the developer tools in your browser, go to the storage tab, and pick cookies from the menu on the left.

Flask cookies are enabled in the developer tools.


Parameters in cookie

You’ll see that cookies contain various options in the developer tools, including key, value, domain, path, and more, which may be configured using Flask. The parameters listed below are passed to the set_cookie function:

Parameter Default value Description
key required The key’s name of the cookie
value “” The cookie’s value
max_age None By default, it is None, but it is the count of seconds
expires None The cookie expiry date, – a datetime object
path None Restricts the cookie to a specific path
domain None set a domain that can read the cookie (default is the initial domain setter)
secure False If True, the cookie is strictly available over HTTPS
httponly False Disallow JavaScript to access the cookie (Limited browser support)
samesite False Limits the scope of where the cookie is accessible to the same site

These features provide us with a lot of control over how our cookies work and many options for managing them. Set the max_age and path keys to 30 seconds, respectively, and the /cookies path to:

To get the current route’s path, we used the request. path. Examining your browser’s developer’s tools console, you’ll notice that our cookie now has an expiry date and a value for path of /cookies. We’ll return to max_age in a moment with another example, but first, let’s go over how to access cookies.

Reading the cookies

Alternatively, use the get() function of the cookies attribute associated with the Request object to read the cookies stored on the client’s system. The file ‘readcookie.html’ contains a link to another view function, getcookie(), which reads the cookie value and shows it in the browser.

The result of setting a cookie & the output of the read-back cookie is in the following complete implementation:


For the website localhost:5000, you can use the preceding python script to set the cookie with the name ‘code,’ and the content ‘underscored’ on the browser.

Use the command python to run this python script and view the results in your browser.

How to use cookies in Flask
set cookie

The cookie details can be tracked in the browser’s content settings, as seen in the figure below.

How to track cookies
How to track cookies

maximum age

Even after changing max_age in our cookie, you may find that it still appears in the developer tools. Remove the first cookie we set by commenting it out:

Refresh the page and wait around 10 seconds. You’ll note in the terminal output that we obtain the following:


Even though the cookie remains in the browser, it is not sent to the server. That is because the max_age value in the cookie has been set to 10 seconds. Upon the browser’s closure, it will be removed. To erase cookies from your browser, right-click on the domain in the developer tools’ cookies tab and select delete.

Deleting cookies

Set the max_age argument to 0 and call set_cookie() with the cookie’s name and any value to erase it. Add the following code directly after the cookie () view method in the file.

Image before deleting the cookie

before deleting cookie
before deleting cookie

Image after deleting the cookie

after deleting cookie
after deleting cookie

Login app in Flask

In this example, we’ll develop a login application in Flask that displays a login page (login.html) to the user and prompts them to input their email and password. If the password is “code,” the application will take the user to the success page (success.html), which includes a message and a link to the user’s profile (profile.html); otherwise, the user will be directed to the error page.


The application’s behavior is managed by the controller python flask script stored as It has the view functions for all of the different instances. The user’s email address is saved in a cookie on the browser. If the user’s password is “code,” the application saves the user’s email address in the browser as a cookie, then read on the profile page to display a message to the user.

The following python and HTML scripts are included in the application. The application’s directory structure is shown below.



Use the command python to run the python script, then go to localhost:5000/ in your browser, as shown in the screenshots.


login interface

Submit the form. It will display a success message as well as a link to profile.html.

login successful
Login successful

or an error message if the credentials do not match.

Error because of incorrect credentials
Error because of incorrect credentials

Select View Profile from the hyperlink shown. It will display the following message after reading the cookie set by the browser as a response.

Cookie’s drawbacks

You should be aware of the drawbacks of cookies before employing them extensively in your project.

Cookies aren’t entirely safe

Because the data stored in the cookie is visible to anybody, you should not use it to store sensitive information such as passwords, credit card numbers, or other personal information.


How to turn off cookies

The majority of browsers allow users to disable cookies. When cookies are disabled, no warnings or error messages are displayed; instead, the response header used to set the cookie is ignored. Use Javascript code to notify the user that your application requires cookies to function correctly to avoid these issues.

Each cookie has a maximum data storage capacity of 4KB. Furthermore, browsers limit the number of cookies that a website can set. This limit changes depending on the browser. Some browsers allow up to 50 cookies per website, while others only allow up to 30.

Every time you request a page from the server, cookies are transmitted. Let’s say you have 20 cookies, each of which has 4KB of data. That means each request has an additional payload of 80KB!

Client-side cookie placement

Using JavaScript to set cookies is also reasonably straightforward.

It will only set the most basic sort of cookie, with no further metadata. We can additionally give the cookie some other parameters, such as:


You can also use the following syntax to add a path:

You can then use request.cookies to access any client-side cookies.


Cookies refer to text files saved on the client’s computer. For a better visitor experience and website statistics, the goal is to recall and track relevant data on consumer usage.

The cookie’s properties are stored in the Flask Request object. It’s a dictionary object that contains all cookie variables and their values and the client. Furthermore, cookies save the website’s expiration time, path, and domain name.


Tag Cloud

Java Java Logical Programs OTP Generation in Java python Recursion youtube video ASCII Upper and Lower Case blockchain javascript graph learn to code software development Successful Software Engineers breadth first search Java Array Programs Java Programs Uncategorized android ios programming kotlin web-development django data sql cybersecurity database swiftui serverless aws swift rust react background-position gradients loader mask grid nth-child pseudo elements indieweb WordPress Print Array without brackets C++ factorial Java String Programs Final Keyword Static Variable Axie Infinity Cryptokitties NFT games tool inserting MISC Tips Codes python code python projects python3 system info python project Bigginers How to Do Integrations Payment Gateways PHP checkout page in php Implement stripe payment gateway in Step by step in PHP integrate stripe gatway in php mysql payment gateway integration in php step by step payment gateway integration in php step by step with source code payment gateway integration in website PHP Integrate Stripe Payment Gateway Tutorial PHP shopping cart checkout code shopping cart in php stripe php checkout PHP/MySQL/JSON best international payment gateway does google pay accept international payments how to accept international payments in india paytm payment gateway razorpay codeigniter github razorpay custom checkout github razorpay get payment details razorpay integration in codeigniter github razorpay international payments Razorpay payment gateway integration in CodeIgniter razorpay payment gateway integration in php code Razorpay payment gateway integration with PHP and CodeIgniter Razorpay payment gateway setup in CodeIgniter Library & Frameworks Tips & Tricks UI/UX & Front-end coding birds online html code for google sign in login with google account in PHP login with google account using javascript login with google account using javascript codeigniter login with google account using php login with google account using php source code
Pandas DataFrame Append explained with examples Previous post Pandas DataFrame Append explained with examples
Next post Higher-Order Functions With TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.