Skip to content

Chi Router: Context Values vs URL Params

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Chi Router: Context Values vs URL Params. We cover key concepts, practical examples, and best practices.

Chi router parameters -- Access URL parameters correctly in Chi router using chi.URLParam() helper instead of direct context lookups.

The Problem

Chi stores URL parameters in the request context using custom keys. Accessing them with r.Context().Value() fails because Chi uses unexported key types. Always use chi.URLParam(r, "key") to extract path variables safely.

Wrong

r := chi.NewRouter()
r.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
    id := r.Context().Value("id") // nil!
})

Output:

$ curl http://localhost:8080/users/42
// id is nil, handler panics on type assertion
r := chi.NewRouter()
r.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
    id := chi.URLParam(r, "id")
    w.Write([]byte("User: " + id))
})

Output:

$ curl http://localhost:8080/users/42
User: 42

Prevention

  • Always use chi.URLParam(r, "key") for path parameters
  • Use chi.URLParamFromCtx(ctx, "key") if you only have a context
  • Use r.URL.Query().Get("key") for query string parameters
  • Chi supports regex: r.Get("/users/{id:[0-9]+}", handler)
  • Middleware can access params via chi.RouteContext(r.Context())

Common Mistakes with router chi

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Does Chi support middleware-specific URL params?**

Yes. Chi.RouteContext holds the params stack.

Can I get all URL params at once?

Access chi.RouteContext(r.Context()).URLParams which is a slice of URLParam structs.

How do I set default values for missing params?

Check: if id := chi.URLParam(r, "id"); id != "" { ... }


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro