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
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:
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.