Back

Error while having 2 Clients on Server SDK

  • 0
  • Self Hosted
  • General
Claas.sh
24 Nov, 2024, 22:24

I got a Problem where I get "API key and session used in the same request. Use either setSession or setKey. Learn about which authentication method to use in the SSR docs: https://appwrite.io/docs/products/auth/server-side-rendering"

I got 2 Clients. One using an API Key and one using the Session

My Dashboard Page:

TypeScript
session, err := r.Cookie("session")
    if err != nil {
        http.Redirect(w, r, "/login", http.StatusSeeOther)
        slog.Warn("Session cookie not found", "IP", r.RemoteAddr)
        return
    }

    sessionClient := appwrite.NewClient(appwrite.WithEndpoint(os.Getenv("ENDPOINT")),
        appwrite.WithProject(os.Getenv("PROJECT_ID")),
        appwrite.WithSession(session.Value))

    Account := appwrite.NewAccount(sessionClient)
    user, err := Account.Get()
    if err != nil {
        http.SetCookie(w, &http.Cookie{
            Name:   "session",
            MaxAge: -1,
        })
        http.Redirect(w, r, "/login", http.StatusSeeOther)
        slog.Warn("Error getting user while creating Account", "error", err)
        return
    }

    tmpl, _ := template.ParseFiles("web/templates/dashboard.html")
    err = tmpl.Execute(w, map[string]interface{}{
        "User":      user,
        "UserCount": backend.GetUsers(),
    })
    if err != nil {
        slog.Error("Error rendering template", "error", err)
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
TL;DR
Error occurs due to using both API key and session in the same request. The solution is to use either `setSession` or `setKey` for authentication. The dashboard page code uses both an API key and a session, causing the error. Developers should choose one authentication method instead.
Claas.sh
24 Nov, 2024, 22:24

The GetUser Function looks like following:

TypeScript
var Client client.Client

func GetUsers() int {
    service := users.New(Client)
    response, err := service.List()
    if err != nil {
        slog.Error("Error getting users while creating session", "error", err)
        return 0
    }

    return response.Total
}

and Client gets set like this:

TypeScript

backend.Client = appwrite.NewClient(
        appwrite.WithEndpoint(os.Getenv("ENDPOINT")),
        appwrite.WithProject(os.Getenv("PROJECT_ID")),
        appwrite.WithKey(os.Getenv("API_KEY")),
    )

When accessing the Dashboard I get the error message because I try to get the amount of total users. Why is that or how would I do it instead?

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more