Sandeep J Patel
Sandeep J Patel

Reputation: 950

How to manage user session and add custom session variables in an AWS Amplify Gen 2 + Next.js project?

How to manage user session and enable profile switching in an AWS Amplify Gen 2 + Next.js project?

I am working on a Next.js project using AWS Amplify Gen 2 and need to implement a profile switching experience for users. Each user should be able to explore two different "flavors" of the application by switching between profiles.

To achieve this, I want to store a current_profile parameter in the session so that:

  1. The selected profile persists across page reloads.
  2. The profile selection can be accessed in both client-side and server-side logic.
  3. The session remains secure and scalable, following best practices in Amplify Gen 2.

However, I couldn’t find any official documentation on session management in Amplify Gen 2. Since Amplify primarily uses Cognito and JWT-based authentication, there is no built-in session handling mechanism like traditional server-side frameworks.

What I’ve Tried:

Questions:

  1. What is the recommended way to store and manage session data in an Amplify Gen 2 + Next.js project?
  2. Is there an official or best-practice approach for profile switching in Amplify Gen 2?
  3. Can I use Amplify server functions or an alternative to maintain the current_profile parameter securely across client and server requests?

Any insights or best practices would be greatly appreciated! 🚀

Upvotes: 0

Views: 25

Answers (1)

Nishit Raval
Nishit Raval

Reputation: 69

You can add a little tag called current_profile to each user’s profile in Cognito.

//amplify/auth/resource.ts
import { defineAuth } from '@aws-amplify/backend';

export const auth = defineAuth({
  loginWith: {
    email: true,
  },
  userAttributes: {
    'custom:current_profile': {
      dataType: 'String',
      mutable: true,
    },
  },
});

When they pick a flavor, you update that tag. It sticks with them because it’s saved in Cognito, and you can grab it whenever you need it—whether you’re loading the page on the server or messing around in the browser.

Upvotes: 0

Related Questions