-
Notifications
You must be signed in to change notification settings - Fork 2.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
runWithAmplifyServerContext with 'cookies' context not working in Server Component #13886
Comments
As a reference, I largely followed this guide for my setup https://docs.amplify.aws/javascript/build-a-backend/server-side-rendering/nextjs-app-router-server-components/ |
Hi @michaelhlf 👋 thanks for raising this issue and providing detailed reproduction steps! I will attempt to reproduce and will report back with any findings. |
Hi @michaelhlf 👋 A quick update - Unfortunately, I was unable to reproduce the issue on the latest version of the I tried creating a Next.js app with a similar setup and did not run into issues executing the provided code. I had to edit the server util file and Server Component a little bit because I don't have the same config file or custom UI components so I just rendered the result of the I did not observe a stack overflow error in the browser console or dev server. I would recommend checking the logic in your components that might be causing an infinite re-render or calling of the function. At the moment, it does not appear to be an issue caused by the Amplify library. Here's the way I configured Amplify in the server utils: import amplify_outputs from "@/amplify_outputs.json";
import { NextServer, createServerRunner } from "@aws-amplify/adapter-nextjs";
import { fetchAuthSession, getCurrentUser } from "aws-amplify/auth/server";
export const { runWithAmplifyServerContext } = createServerRunner({
config: {
Auth: {
Cognito: {
userPoolId: amplify_outputs.auth.user_pool_id,
userPoolClientId: amplify_outputs.auth.user_pool_client_id,
identityPoolId: amplify_outputs.auth.identity_pool_id,
},
},
},
});
// Existing function to get the authenticated user
export async function authenticatedUser(
context: NextServer.Context,
refreshIfNotSubscriber = false
) {
return await runWithAmplifyServerContext({
nextServerContext: context,
operation: async (contextSpec) => {
try {
let session = await fetchAuthSession(contextSpec);
if (!session.tokens) {
return;
}
let user = {
...(await getCurrentUser(contextSpec)),
isSubscribed: false,
};
let groups = session.tokens.accessToken.payload["cognito:groups"];
// @ts-ignore
user.isSubscribed = Boolean(groups && groups.includes("Subscriber"));
if (refreshIfNotSubscriber && !user.isSubscribed) {
session = await fetchAuthSession(contextSpec, { forceRefresh: true });
if (!session.tokens) {
return;
}
user = {
...(await getCurrentUser(contextSpec)),
isSubscribed: false,
};
groups = session.tokens.accessToken.payload["cognito:groups"];
// @ts-ignore
user.isSubscribed = Boolean(groups && groups.includes("Subscriber"));
}
return user;
} catch (error) {
console.log(error);
}
},
});
} Here's my server component: import React from "react";
import { authenticatedUser } from "@/utils/amplify-server-utils";
import { cookies } from "next/headers";
import { Metadata } from "next";
export const metadata: Metadata = {
title: "Learn",
description: "Browse our learning paths",
};
const Learn = async () => {
const user = await authenticatedUser({ cookies });
return (
<div className="w-80 h-3">
<pre>{JSON.stringify(user, null, 2)}</pre>
</div>
);
};
export default Learn; When I navigate to |
Hi @chrisbonifacio, thanks for trying to reproduce the error. Could you possibly run console.log(cookies) in your server component and post what the output is? I'm wondering if something in my setup could be altering the structure of these cookies, |
update: after stumbling across this ticket #13413, I realised my authConfig object being used to initialise the server runner was being exported from a module with the 'use client' directive. After moving the definition of this auth object to another server module, the issue is resolved! |
Ah, nice find! Thank you for sharing the solution 🙏 |
Before opening, please confirm:
JavaScript Framework
Next.js
Amplify APIs
Authentication
Amplify Version
v6
Amplify Categories
auth
Backend
Other
Environment information
Describe the bug
When using the runWithAmplifyServerContext ( in order to run fetchAuthSession(contextSpec)) created with createServerRunner() in a Nextjs 14 Server component, using {cookies} as a context causes a stack overflow error. runWithAmplifyServerContext works as expected when called from Nextjs middleware (middleware.ts), again passing in {cookies} as context, as imported with 'import { cookies } from 'next/headers';'
Expected behavior
calling my authenticatedUser() function (which uses runWithAmplifyServerContext ) should return the current user session info as it does when calling from middleware.ts
Reproduction steps
Code Snippet
in utils/amplify-server-utils.ts
And in learn/page.tsx
Log output
As mentioned, when the same function is called from middleware, passing in the cookies (imported from next/headers in exactly the same way ) everything works as expected
Interestingly, the value of 'cookies' does seem to be different, when simply using console.log to show the cookies object (or function?) depending if it is logged from middleware or the server component.
From the middleware
and from the Server component
aws-exports.js
No response
Manual configuration
No response
Additional configuration
No response
Mobile Device
No response
Mobile Operating System
No response
Mobile Browser
No response
Mobile Browser Version
No response
Additional information and screenshots
This occurs both locally, using next dev, and when deployed to my live environment. This is deployed to AWS using SST Ion
The text was updated successfully, but these errors were encountered: