Sharing golang gin session with next.js

Utilizing the latest version of Next.js v14.2.3 and App Router.

I am currently implementing cookie-based sessions from the gin-contrib documentation, in order to increase a session count.

    // Backend Golang code snippet
    ...
    cookieStore := sessions.NewCookieStore([]byte("secret"))
    router.Use(
        sessions.Sessions("mysession", cookieStore),
    )

    router.GET("incr", func(c *gin.Context) {
        session := sessions.Default(c)
        c.Header("Content-Type", "application/json")

        var count int
        v := session.Get("count")
        if v == nil {
            count = 0
        } else {
            count = v.(int)
            count++
        }
        session.Set("count", count)
        session.Save()
        c.JSON(200, gin.H{"count": count})
    })
    ...

Testing with Postman shows that the cookie session is present in the response and the counter increments with each request. (However, I've noticed that curl includes headers and a mysession cookie)

curl --location 'localhost:8080/incr' \
--header 'Cookie: mysession=someLongKey='

Should I include this header in my fetch request? And how do I retrieve the someLongKey value to send with the request?

Currently, when attempting to make this request using fetch in a Next.js project.

        // Frontend Next.js code snippet
        const resp = await fetch(`${process.env.BACKEND}/incr`)
        const res = await Promise.all([resp.json()])
        console.log("this is the res ",res)

The output does not increment as expected,

this is the res  [ { count: 0 } ]
 POST /incr 200 in 16ms
this is the res  [ { count: 0 } ]
 POST /incr 200 in 17ms
this is the res  [ { count: 0 } ]
 POST /incr 200 in 15ms
this is the res  [ { count: 0 } ]

Additionally, upon inspecting the browser developer tools, the cookie is not visible in the response.

Answer №1

Referencing the mdn web docs, I have made updates to the JavaScript code

...
const resp = await fetch(`${process.env.BACKEND}/incr`)
const cookie = resp.headers.get("set-cookie")
console.log("The cookie is: ",cookie)
...

The response cookies can be found in the headers.

Using this obtained cookie value to fetch again:

        const resp = await fetch(`${process.env.BACKEND}/incr`,{
            headers:{
                Cookie:`cookieValueFromAbove`
            }
        })

Now, the counter increments as expected

this is the res  [ { count: 1 } ]
 POST /incr 200 in 58ms
this is the res  [ { count: 2 } ]
 POST /incr 200 in 52ms

By consolidating information from next.js cookie and headers documentation, I developed a middleware.ts file

...
export default async function middleware(request:NextRequest){
    const response = NextResponse.next();
    const cookieStore = cookies()
    let cookie = cookieStore.get('set-cookie')
    let header = ""
    if(!cookie) {
        console.log("Need to fetch from gin to get cookie from response")
        const initialPromise = await fetch(`${process.env.BACKEND}/incr`)
        header = initialPromise.headers.get('set-cookie')
        console.log("Received response cookie",header)
    } else {
        console.log("Final cookie obtained",cookie)
        response.headers.set('set-cookie',cookie.value)
    }

    return response
}
...

Updating the function within scr/app/lib/actions.ts

...
export async function incr(...){
        const initialHeaders = headers().get('set-cookie')
        const initialPromise = await fetch(`${process.env.BACKEND}/incr`,{
            headers:{
                cookie:initialHeaders
            },
        })

        const updatedHeaders = initialPromise.headers.get('set-cookie')
        cookies().set("set-cookie",updatedHeaders)
}

The results are as follows:

this is the res  [ { count: 43 } ]
 POST /incr 200 in 58ms
this is the res  [ { count: 44 } ]
 POST /incr 200 in 26ms
this is the res  [ { count: 45 } ]
 POST /incr 200 in 23ms
this is the res  [ { count: 46 } ]
 POST /incr 200 in 22ms
this is the res  [ { count: 47 } ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reveal the administrator's details exclusively when the associated radio button is chosen

Managing administrators for a post can be done through an editing page with corresponding radio buttons. Each radio button is linked to a different administrator, and selecting one populates the form fields with that admin's details. The issue arises ...

Experiencing an unexpected abundance of console logs when implementing React Hooks

I am attempting to retrieve data from an API. The desired result is being obtained, but when I attempt to log it to the console, it logs 4 times. Within my app.js, I am utilizing the fetchData function: import React, {useEffect, useState} from 'rea ...

Having trouble with the functionality of expanding rows in Kendo grid

I am facing an issue with my Kendo grid that is populated from a SQL database. The expand feature works perfectly and displays a different Kendo grid in the expanded row when the program is first launched. However, if I perform a new search and get differe ...

Tips on preventing Next.js from showing a loading state across the entire page when a specific section of the page sends a request

On my nextjs page, I'm using the loading.tsx approach which displays a loading spinner until the entire page is loaded. This works great, but I have encountered an issue with a popup card that loads upon hovering over a certain element. The problem ar ...

What is the best way to organize notifications by dates in a React application?

I'm currently working on a notifications component where I need to sort notifications by dates and then display them. Although I attempted the following code, it didn't work as intended: const result = notifications.notificationRows.sort((a, b) ...

The Angular multi select tree feature seems to be malfunctioning

I recently incorporated a plugin called angular-multi-select-tree from GitHub into my project. Here is how I added it: First, I installed it via bower using the command bower install angular-multi-select-tree --save. This updated the bower.json file to i ...

Updating the time and date format within an AngularJS application

I am receiving date and time data from the API and would like to adjust the format. The current format is "2016-05-12", "07:17:35". Desired format: 12-May-2016 7:30 PM: <table class="table"> <thead> <tr> <th& ...

Search through a JSON object, identify all keys that start with the same letter, and transfer them to a new JSON data structure

I am looking to iterate through my JSON data and extract all keys along with their values that start with the letters "QM". Below is an example of my JSON content: [ { MHF46: 'Ledig', MHF181: '06', QM6_QMSI2: '1899-12-30 ...

How to Stop Element Flickering While Hovering in Selenium IE Webdriver

My code is functioning perfectly in Firefox, but when I try it on Internet Explorer, there is flickering. Here is my code: WebElement mouseOver= driver.findElement(By.linkText("abc")); //I'm locating the element by link text. Selenium finds the ...

Ways to implement JavaScript code in Angular 7 application

I am attempting to create a collapsible navigation bar using MaterializeCSS for mobile screens and I plan to incorporate JavaScript code into it. Can you advise where I should place this JavaScript code? Below is the snippet of code that I intend to inclu ...

Trouble arises when trying to combine NextJs 12.2.5 with next-auth 4.17 due to a dependency

npm ERROR! Could not find a solution for the dependency: npm ERROR! required peer next@"^12.2.5 || ^13" by [email protected] npm ERROR! in node_modules/next-auth npm ERROR! next-auth version is "*" as defined in the root project ...

Unable to submit /api/sentiment

I'm currently troubleshooting the /api/sentiment endpoint in postman and encountering a "cannot POST" error. I have confirmed that the routes are correct and the server is actively listening on port 8080. Interestingly, all other endpoints function wi ...

Guide on sending an AJAX request to a server

I'm currently working on implementing AJAX and have encountered a roadblock. Specifically, I need assistance with sending a request to the server when a user clicks on a specific image, expecting the server to return that image. While I know how the s ...

In React, when pushing to an array, it is the index that gets returned instead of the items

I'm currently working on incorporating a new object into an array that I'm fetching dynamically through my API. Users fill out a form, and the data is transmitted from the form to the state. The initial fetch stores the original array in a React ...

Unable to save a URL link in MySQL database using JSON and PHP

I am seeking some insightful advice regarding my college assignment. This time around, I have to create yearbooks using Phonegap and it's my first experience working with AJAX, JSON, and JQuery Mobile. Instead of uploading an image directly into the ...

Container slide-show fill error

I'm attempting to create a slide show with an overlapping caption that appears when hovering over the container or image. The image needs to fit exactly inside the container so no scroll bar is shown and the border radius is correct. I managed to achi ...

jQuery load() function triggers unexpected error in jQuery plugin

Here is the current structure of my page: <body> <div id="menuBar"> </div> <canvas id="myCanvas" width="700" height="700" style="border:1px solid #000000;"></canvas> </body> <script src="../Scripts/jQuery.mazeBo ...

Switch between two distinct menus (Reactjs + Material UI)

Recently, I designed a robust menu system that includes a Switcher feature. The concept is straightforward - if the switch is turned off, display the 1st menu; and if it's on, show the second menu. However, there seems to be an issue. When the switch ...

Assign local variable in Mongoose using query results

I created a function to query MongoDB for a credential (simplified): var query = Credential.findOne({token: token}); return query.exec(function (err, credential) { if (err) return null; return credential; }); The next step is to use this credent ...

Using jQuery to pass dynamic values to a plugin function

I'm currently utilizing the JSONTable plugin and attempting to dynamically pass values to the 'head' and 'json' parameters by extracting them from an array object. For instance, I aim to load a new json file, convert it to a JavaSc ...