> ## Documentation Index
> Fetch the complete documentation index at: https://docs.go-mizu.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Cookies

> Learn how to manage cookies data.

In this lesson, you will learn how to use cookies in Mizu to store and read small pieces of data between requests.<br />
Cookies are a simple way to remember users, track sessions, or save preferences like language or theme. Mizu provides two helpers, `Ctx.Cookie()` and `Ctx.SetCookie()`, that make cookie handling easy.

### Code

Create a file named `main.go` and add this code:

```go theme={null}
package main

import (
	"log"
	"net/http"
	"time"

	"github.com/go-mizu/mizu"
)

// Set a cookie named "username"
func setCookie(c *mizu.Ctx) error {
	name := c.Query("name")
	if name == "" {
		name = "Guest"
	}

	c.SetCookie(&http.Cookie{
		Name:     "username",
		Value:    name,
		Path:     "/",
		HttpOnly: true,
		Expires:  time.Now().Add(24 * time.Hour),
	})

	return c.Text(http.StatusOK, "Cookie set for "+name)
}

// Read a cookie named "username"
func getCookie(c *mizu.Ctx) error {
	cookie, err := c.Cookie("username")
	if err != nil {
		return c.Text(http.StatusNotFound, "No cookie found")
	}
	return c.Text(http.StatusOK, "Welcome back, "+cookie.Value)
}

// Delete the cookie by setting expiration to the past
func clearCookie(c *mizu.Ctx) error {
	c.SetCookie(&http.Cookie{
		Name:    "username",
		Value:   "",
		Path:    "/",
		Expires: time.Unix(0, 0),
		MaxAge:  -1,
	})
	return c.Text(http.StatusOK, "Cookie cleared")
}

func main() {
	app := mizu.New()

	app.Get("/set", setCookie)
	app.Get("/get", getCookie)
	app.Get("/clear", clearCookie)

	if err := app.Listen(":8080"); err != nil {
		log.Fatal(err)
	}
}
```

### Run

Start the server:

```
go run .
```

Then try the following examples:

#### Set a cookie

Visit [http://localhost:8080/set?name=Alice](http://localhost:8080/set?name=Alice)
Response: `Cookie set for Alice`
Your browser now stores a cookie named `username`.

#### Get the cookie

Visit [http://localhost:8080/get](http://localhost:8080/get)
Response: `Welcome back, Alice`
The value comes from the cookie you set earlier.

#### Clear the cookie

Visit [http://localhost:8080/clear](http://localhost:8080/clear)
Response: `Cookie cleared`
The browser cookie is now deleted.

### How it works

| Method                         | Purpose                           | Example                                                            |
| ------------------------------ | --------------------------------- | ------------------------------------------------------------------ |
| `c.SetCookie(ck *http.Cookie)` | Sends a cookie to the client      | Sets name, value, expiry, and options like `HttpOnly` or `Secure`. |
| `c.Cookie("name")`             | Reads a cookie sent by the client | Returns a `*http.Cookie` and an error if not found.                |

* Setting a cookie adds a `Set-Cookie` header to the HTTP response.
* Reading a cookie checks the request headers for the matching cookie name.
* Deleting a cookie works by sending a new cookie with an empty value and an expiration date in the past.

This approach lets you manage sessions or preferences without needing a database or external storage.

### Try something new

Add a handler that counts how many times a user has visited your site:

```go theme={null}
func visitCount(c *mizu.Ctx) error {
	ck, _ := c.Cookie("visits")
	count := 0
	if ck != nil {
		fmt.Sscanf(ck.Value, "%d", &count)
	}
	count++

	c.SetCookie(&http.Cookie{
		Name:    "visits",
		Value:   fmt.Sprintf("%d", count),
		Path:    "/",
		Expires: time.Now().Add(24 * time.Hour),
	})

	return c.Text(http.StatusOK, fmt.Sprintf("You have visited %d times", count))
}
```

Register it with `app.Get("/visits", visitCount)` and refresh the page several times.
The count will increase with each visit.

Cookies form the basis for session handling, login tracking, and simple user personalization.
Next, continue to [Middleware Basics](./008-middleware-basics) to learn how to wrap your handlers with reusable logic like logging, timing, and authentication.
