Check if the user is authenticated on the initial request

Viewed 901

I am using nuxt + aws amplify for the web app and I need to check if the user is authenticated to load the page details depending on that. I configured amplify so the user credentials are stored in the cookie instead of the local storage so all the information about the user can be retrieved from req.headers.cookie, but the code below

async nuxtServerInit (props, ctx) {
  const { Auth } = withSSRContext(ctx)
  try {
    const cognitoUser = await Auth.currentAuthenticatedUser()
    console.log(cognitoUser)
  } catch(error) {
    console.error(error)
  }
},

gives The user is not authenticated

My amplify config:

Amplify.configure({
    sst: true,
    Auth: {
        identityPoolId: process.env.IDENTITY_POOL_ID,
        userPoolId: process.env.USER_POOL_ID,
        userPoolWebClientId: process.env.USER_POOL_CLIENT_ID,
        region: 'eu-central-1',
        mandatorySignIn: false,
        cookieStorage: {
            domain: isDev ? 'localhost;' : '.website.my',
            path: '/',
            expires: 1,
            sameSite: 'strict',
            secure: !isDev
        },
        authenticationFlowType: 'USER_PASSWORD_AUTH'
    }
})

Login and auth work fine on client-side.

2 Answers

I found out that the issue was in the configuration, when using ssr: true you are not allowed to add manual configuration for cookies. So the solution here is just removing this block

cookieStorage: {
  domain: isDev ? 'localhost;' : '.website.my',
  path: '/',
  expires: 1,
  sameSite: 'strict',
  secure: !isDev
},
Related