skip to Main Content

I’m working on a Next.js project and I need to store the userId after a user logs in. This userId is essential for fetching user-specific data and generating dynamic URLs for the user profile menu.

Here’s the workflow I’m trying to implement:

  1. User logs in.
  2. Store the userId securely.
  3. Use the stored userId to fetch user-specific data.
  4. Generate dynamic profile URLs like /profile/{userId}.

What is the best practice to securely store the userId and retrieve it for generating the dynamic profile URLs? Should I use cookies, local storage, or another method? How can I ensure that this approach is both secure and efficient?

Here’s a snippet of my login function:

const handleLogin = async () => {
  const response = await fetch('/api/login', {
    method: 'POST',
    body: JSON.stringify({ username, password }),
  });
  const data = await response.json();

  if (data.success) {
    // How to securely store data.userId for later use?
  }
};

In the best case, I can use either userId on the client side and also on the server side

2

Answers


  1. You can encrypt your session and set cookies on server side
    Here is a good example in nextjs docs for doing the same

    https://nextjs.org/docs/app/building-your-application/authentication#2-encrypting-and-decrypting-sessions

    Login or Signup to reply.
  2. The best practice for storing and getting userId on both client and server side is to store it in cookies. Cookie is faster and more secured compared to localstorage. Although cookie has some limitations like you cannot mutate cookie on the server side but you can read them on the server side. To set or delete a cookie, you need to use a client component. Another limitation that I noticed was you cannot store large objects in cookie as it has a limitation of 4096 bytes but I think that will be more than enough to store userId and other session informations.
    I’m suggesting you a package which is best for handling cookies in nextjs named cookies-next.

    assuming that the function is called from a client component:

     const handleLogin = async () => {
      const response = await fetch('/api/login', {
        method: 'POST',
        body: JSON.stringify({ username, password }),
      });
      const data = await response.json();
    
      if (data.success) {
        // How to securely store data.userId for later use?
        setCookie('userId', data.userId, { maxAge: 60 * 6 * 24 });
      }
    };
    

    I’d be more than happy to hear from you if you need more assistance. Thank you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search