Error fetching data: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

122 views Asked by At

im having problems with gorilla sessions mainly, but with nextjs and frontend too, i can fetch all my data with no problem, but when i try to send the user to the front end from the gorilla session cookie, the user always endup being null, which is weird because if i use postman, not only the values are right, but the user is not null like in the browser.

the code bellow is where i start my echo api, set my cors, start the gorilla session store with the secret and set my home api route:

    e := echo.New()

    e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
    AllowOrigins: []string{"http://localhost:3000"},
    AllowCredentials: true,
    }))

    e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret"))))

    e.GET("/api/recipes", Home)

the function bellow is what returns when i fetch from the backend, im having a problem with the "!ok" part, it always returns as true when i try to run in my browser with my frontend instead of postman or just the backend call with the browser

func Home(c echo.Context) error {
    recipes, err := models.GetAllRecipes()

    if err != nil {
        return err    
    }

    sess, err := session.Get("session", c)
    
    //This code below is where im having the issue
    sessionData, ok := sess.Values["user"]
    if !ok {
        return err
    }
    response := map[string]interface{}{
        "recipes": recipes,
        "user": sessionData,
    }

    return c.JSON(http.StatusOK, response) 
}

this is my login function where i create the cookie with gorilla sessions when i login

func PostLogin(c echo.Context) error {
    user := new(models.UserLogin)

    if err := c.Bind(user); err != nil {
        return err
    }

    err := models.LoginUser(user)

    if err != nil {
        return err
    }
    sess, _ := session.Get("session", c)
    sess.Options = &sessions.Options{
        Path: "/",
        MaxAge: 86400 * 7,
        HttpOnly: true,
    }
    sess.Values["user"] = user.Username
    err = sess.Save(c.Request(), c.Response())
    if err != nil {
        return err
    }

    return c.JSON(http.StatusOK, "User Logged In")
}

where i fetch in the frontend (the catch error is where i get the error back)

export const getServerSideProps: GetServerSideProps<{
  data: RecipeData;
}> = async () => {
  try {
    const res = await fetch("http://localhost:4000/api/recipes");
    const data: RecipeData = await res.json();
    console.log("API Response:", data); // Add this line for debugging
    return { props: { data } };
  } catch (error) {
    console.error("Error fetching data:", error);
    return { props: { data: { recipes: [], user: "" } } };
  }
};

example of data that i should get back:

{
    "recipes": [
        {
            "id": 2,
            "title": "egg",
            "ingredients": "egg",
            "instructions": "egg",
            "categories": "main-course"
        }
    ],
    "user": "carlos"
}

instead i always get the user as null using the browser because the !ok returns as true with gorilla sessions

some notes that could help:

i dont think is either problems with cors or with the cookies, i tried a lot of things and i didnt make a difference.

When i look in the network tab in the browser, everything returns as get 200 status code with no problems

i get no errors in the devtools console in the browser, just the user as null that i tried to log for debugging

0

There are 0 answers