Unable to use aws-amplify with NextJS 13.4 api routes
Asked Answered
M

1

7

I have successfully used pages/api routes in previous versions of NextJS to connect to AWS API Gateway. I'm trying to use new app router to do the same thing in app/api/route. But I'm unable to get the aws-amplify libraries working, i.e.

const {Auth: ssrAuth} = withSSRContext({ req: request });  //works
const user = await ssrAuth.currentAuthenticatedUser();     //fails

This works fine with page router and I'm able to get the user token to attach the authorizer to the API Gateway request.

Any idea why? The request is there and I can see the cookie with the user token. What am I doing wrong?

Any feedback/tip much appreciated

Mcnalley answered 10/5, 2023 at 3:44 Comment(0)
M
7

As often the case, the solution was pretty simple. The answer laid deep in the Amplify docs

Amplify JavaScript can be used with the Next.js App Router (Next.js v13.4+) by applying the following changes:

  1. Run Amplify.configure({ ...awsExports, ssr: true }) in both the client-side and server-side code

To use Amplify with Next.js App Router, you must run Amplify.configure() in both Client and Server Components. The ssr option must be enabled.

So, in my case, I already had Amplify.configure on the client when I connected to AWS Cognito with Auth Context. So, now I just had to add the same thing to the common library used by every route file to build axios config object. And it magically worked! Apparently, both sides need to have a separate access to env variables. It kinda makes sense, but some better documentation with more examples would be great.

Mcnalley answered 16/5, 2023 at 5:25 Comment(2)
Will it work with next 12?Command
It's different for pre-nextJS 13. You don't have to reconfigure amplify. In fact, I recently found out that you don't have to reconfigure Amplify at all. All tokens are accessible from the session that's part of the request. Amplify has methods to help you access it: currentAuthenticatedUser()Mcnalley

© 2022 - 2024 — McMap. All rights reserved.