How to manage cookies with Hapi

When you visiting the most of all sites in internet, you see the messages about cookies. Cookies it’s a small piece of data, which sends with every request to server. Cookies allow to get more information about what user do on site during the session. In Hapi, you can simply start to work with cookies without any libraries.

Setting a global cookie

To set HTTP cookie we should you the .state method of server instance. The first argument – the cookie name, the second – options. Options object accepts the next popular properties:

KeyValue description
isHttpOnlyhttpOnly flag, the default value – true
ttltime to live of session, the default value – null
isSecuresecure flag, the default value – true
encodingtype of encoding, the default value – ‘none’, other values – ‘base64’, ‘base64json’, ‘form’, ‘iron’

About other properties you can read in the official Hapi documentation.

In the following example, we will set the cookie for one day and called it testCookie:

Setting a cookie for route

If you want to set cookie for a specific route, you need to set the options.state object (to parse and store cookies) in route handler and use the .state method of response object or response toolkit:

When you reach  GET /index endpoint, you should see the following response headers in browser:

Custom route cookie
Custom route cookie

Getting a cookie

All cookies will store in req.state object and can be accessed by the name of cookie as property of req.state:

Deleting a cookie

To remove a cookie, you can use the .unstate('cookieName'). For example. the cookie with name  testCookie can be cleared like this:

If you liked this, please help spread the word by hitting the recommend button below. Thanks!

Tags:,