Farhad Mirzaei
Farhad Mirzaei

Reputation: 43

Can't get the cookies from golang server inside the react js project

I have a simple server written on Golang and it's supposed to handle login requests and set some cookies. But the problem is that i cant access the cookies inside my React Js project I set the cookies with this code:

        if OTPValidate.Result.Status == "success" {
        log.Println("Setting Cookies")
        session := sessions.DefaultMany(ginContext, "session")
        session.Set("MobileNumber", Number)
        session.Set("GUID", OTPValidate.GUID)
        session.Set("PersonId", OTPValidate.PersonID)
        if err != nil {
            logger.Error(logger.FuncName() + err.Error())
        }
        session.Options(sessions.Options{MaxAge: 2592000}) // 30 Day
        session.Save()
    }

and currently using Cookies Js to get the cookies:

    const cookie = Cookies.get('session')
    console.log(cookie)

but it prints undefined I checked the request header inside the network tab in the browser and it seems fine:

Network Tab Screenshot

But still I'm not able to get them into the react

Upvotes: 4

Views: 1043

Answers (1)

thrownew
thrownew

Reputation: 115

It is unacceptable to provide access from JS to authorization cookies, this will lead you to serious incidents with the loss of user access to their accounts: https://en.wikipedia.org/wiki/Secure_cookie.

But if you still want do it, as Osman said in comments, you need to be sure you set cookie right way:

http.SetCookie(w, &http.Cookie{
    Name:     `session`,
    Value:    url.QueryEscape(sid),
    Expires:  time.Now().Add(time.Hour),
    Path:     "/",
    Secure:   false, // Secure = false allow to access from js
    HttpOnly: true,
    SameSite: http.SameSiteNoneMode,
})

Upvotes: 1

Related Questions