Next.js Discord

Discord Forum

Using aws amplify only stores session in frontend, how do I access it in backend

Answered
Siricid woodwasp posted this in #help-forum
Open in Discord
Avatar
Siricid woodwaspOP
While this does store session in cookies but I dont have access to resources in server such as getUser()

export async function handleSignIn({ username, password }: SignInInput) {
  try {
    const { isSignedIn, nextStep } = await signIn({
      username,
      password,
      options: { authFlowType: "USER_SRP_AUTH" },
    });

    if (isSignedIn) {
      console.log("signed in");
      const session = await fetchAuthSession();
      console.log("session", session);
      cognitoUserPoolsTokenProvider.setKeyValueStorage(new CookieStorage());
    }
  } catch (error) {
    console.log("error signing in", error);
  }
}
Answered by Ray
import { cookies } from 'next/headers';
import { getCurrentUser } from '@aws-amplify/auth/server';
import { runWithAmplifyServerContext } from '@/utils/amplifyServerUtils';

// This page always dynamically renders per request
export const dynamic = 'force-dynamic';

export default async function AuthGetCurrentUserServer() {
  try {
    const currentUser = await runWithAmplifyServerContext({
      nextServerContext: { cookies },
      operation: (contextSpec) => getCurrentUser(contextSpec)
    });

    return (
      <AuthFetchResult
        description="The API is called on the server side."
        data={currentUser}
      />
    );
  } catch (error) {
    console.error(error);
    return <p>Something went wrong...</p>;
  }
}
View full answer

5 Replies

Avatar
Siricid woodwaspOP
but then I dont have access to anything at frontend
Avatar
Ray
backend mean external backend or you mean server side?
Avatar
Siricid woodwaspOP
server side
Avatar
Ray
import { cookies } from 'next/headers';
import { getCurrentUser } from '@aws-amplify/auth/server';
import { runWithAmplifyServerContext } from '@/utils/amplifyServerUtils';

// This page always dynamically renders per request
export const dynamic = 'force-dynamic';

export default async function AuthGetCurrentUserServer() {
  try {
    const currentUser = await runWithAmplifyServerContext({
      nextServerContext: { cookies },
      operation: (contextSpec) => getCurrentUser(contextSpec)
    });

    return (
      <AuthFetchResult
        description="The API is called on the server side."
        data={currentUser}
      />
    );
  } catch (error) {
    console.error(error);
    return <p>Something went wrong...</p>;
  }
}
Answer