英文:
Unable to use aws-amplify with NextJS 13.4 api routes
问题
我之前在 NextJS 的旧版本中成功使用了页面/api路由来连接到 AWS API Gateway。我试图使用新的应用程序路由器在 app/api/route 中做同样的事情。但我无法让 aws-amplify
库正常工作,即
const {Auth: ssrAuth} = withSSRContext({ req: request }); //works
const user = await ssrAuth.currentAuthenticatedUser(); //fails
这在页面路由中运行良好,我能够获取用户令牌并将其附加到 API Gateway 请求的授权者。
有什么想法吗?请求是存在的,我可以看到带有用户令牌的 cookie。我做错了什么?
任何反馈/提示都非常感谢
英文:
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
答案1
得分: 6
按照通常情况,解决方案非常简单。答案深藏在 Amplify 文档 中。
在 Next.js 应用路由器(Next.js v13.4+)中,可以通过以下更改使用 Amplify JavaScript:
- 在客户端和服务器端代码中运行 Amplify.configure({ ...awsExports, ssr: true })
> 要在 Next.js 应用路由器中使用 Amplify,
> 您必须在客户端和服务器端组件中运行 Amplify.configure()。
> 必须启用 ssr 选项。
所以,在我的情况下,当我连接到 AWS Cognito with Auth Context 时,客户端已经有了 Amplify.configure
。所以,现在我只需将相同的内容添加到每个路由文件都使用的通用库中,以构建 axios 配置对象。神奇的是,它就奏效了!显然,两侧都需要单独访问环境变量。这有点合理,但更多带有示例的更好文档会更好。
英文:
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:
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论