Getting "not authenticated" Error in Nuxt.js middleware with SSR and Amplify

Viewed 846

I would like to create a Nuxt.js middleware to check if an user is authenticated or not. That works fine while navigation inside of the app. But when I refresh the page I always get:

[ERROR] 43:48.846 foo - SERVER {                                                                  15:43:48  
  error: 'not authenticated'
}
 ERROR  [ERROR] 43:48.844 AuthError -                                                                     15:43:48  
        Error: Amplify has not been configured correctly.
        The configuration object is missing required auth properties.
        Did you run `amplify push` after adding auth via `amplify add auth`?
        See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information
  1. AWS Amplify has an article with SSR Support here: SSR Support for AWS Amplify There you can find the code to enable SSR and checking for user authentication

  2. In the Nuxt.js Docs, you can find:

In universal mode, middlewares will be called once on server-side (on the first request to the Nuxt app, e.g. when directly accessing the app or refreshing the page) and on the client-side when navigating to further routes.

Alright, so I enabled SSR in my amplify plugin and adjusted the middleware:

if (process.server) {
const { Auth } = withSSRContext(context.req)
try {
  await Auth.currentAuthenticatedUser()
} catch (error) {
  return context.redirect(302, '/auth/signin')
}

}

When I refresh the page, the code gets executed, but I always get a "not authenticated" error and "Amplify has not been configured correctly". On the other hand everything works perfectly fine on client side (signin, signup, etc.)

Any idea guys? I can't find a solution...

Kind regards

2 Answers

I ran in to the same problem and it turned out I had to adjust my configuration. I'm in NextJS but it looks like the same issue. In changed the way I configured Amplify in my component from:

Amplify.configure({ ...config })

to

Amplify.configure({ ...config, ssr: true })

Without setting the ssr property, my server side code was not able to pickup the current authenticated user and all I got was 'The user is not authenticated' in the server logs.

I'm using aws-amplify@3.3.4

Just try to configure Auth. No need to provide ssr: true. At least thats what worked for me..

if (process.server) {
const { Auth } = withSSRContext(context.req)
Auth.configure({...config})
try {
  await Auth.currentAuthenticatedUser()
} catch (error) {
  return context.redirect(302, '/auth/signin')
}
Related