DEV Community

Paul Akinyemi
Paul Akinyemi

Posted on

Solving the "session store not found" error while testing handlers in Echo

Just a quick tip to make the solution for this easier to find. If you're having this problem, you most likely have code similar to this in your test:

e := echo.New()
e.Use(session.Middleware(sessions.NewCookieStore([]byte(sessionKey))))
c := e.NewContext(req, resp)
sess, err := session.Get("user-session", c)
Enter fullscreen mode Exit fullscreen mode

And your call to session.Get() returns the "session store not found" error. Here's what the source code for Get() looks like:

const (
    key = "_session_store"
)

// Get returns a named session.
func Get(name string, c echo.Context) (*sessions.Session, error) {
    s := c.Get(key)
    if s == nil {
        return nil, fmt.Errorf("%q session store not found", key)
    }
    store := s.(sessions.Store)
    return store.Get(c.Request(), name)
}
Enter fullscreen mode Exit fullscreen mode

Your call to Get() throws an error because Get() checks the context you pass to it for the session_store key, but the context returned by e.NewContext() is completely blank, unlike the context echo passes to your handlers when serving HTTP requests.

To solve the error, before you make any calls to Get() you need to set a cookie store on the context returned by e.NewContext() with the key _session_store.

You can do that like this:

e := echo.New()
c := e.NewContext(req, resp)
c.Set("_session_store", sessions.NewCookieStore([]byte(sessionKey)))
sess, err := session.Get("user-session", c)
Enter fullscreen mode Exit fullscreen mode

And that will take care of the error.

Top comments (0)