Search code examples
node.jscookieswebbrowser-controlnext.js13

Create a unique UserToken for a browser to track user without login in Nextjs 13


I am trying to build a game very similar to https://www.moviegrid.io/, This Game generates some clues on the basis of the user guessing movies when the user guesses the first movie or tries to guess doesn't matter if the guess is true or false a unique token is generated to keep its session as this keep hold the clues for a days and refresh clues at specific time, so let us suppose i guessed a movie and its not true so my guess tried decrease from 9 to 8 now if i refersh the page or open game in new tab or close browser and open game i see that my guesses record are available and there is unique token that is used to get my record from database , I figured out all the logic just want to know how can i keep track of user as he never logged in , as this is something i never done before is it possible to create token that identify the browser or device i have no clue about this


Solution

  • It is possible to track sessions without login with the help of cookies. You can identify a user who has previously used your website by storing a cookie in the user's browser and retrieving it the next time when the user comes back to your website. The cookie should have some sort of information which could be used to query your database to find information regarding the user.

    Here's example code which utilizes NextJS's cookie function inside of a server action to track user sessions.

    Step 1: Set a cookie on the user's browser.

    'use server'
    
    import { cookies } from 'next/headers'
     
    async function setSessionCookie(key) {
      cookies().set({
        name: 'sessionID',
        value: key, // `key` can refer to the `token` you refer to in the question
        httpOnly: true,
      });
    }

    Note that setting the httpOnly property to true ensures that the cookie can be accessed by the server only and not by any client side scripts running on the user's browser.

    Step 2: Retrieve the cookie.

    import { cookies } from 'next/headers'
     
    function getSessionCookie() {
      const cookieStore = cookies();
      const sessionKey = cookieStore.get("sessionID");
      return sessionKey;
    }

    You can use the above code to identify a user who has previously used your website.

    To learn more about how to work with cookies in NextJS, view the docs