How to use AWS Amplify Authentication with Next.js Server Actions
No next-auth required:
// amplifyServerUtils.ts
import { createServerRunner } from '@aws-amplify/adapter-nextjs';
import config from '@/amplifyconfiguration.json';
export const { runWithAmplifyServerContext } = createServerRunner({
config
});
// actions.ts
"use server";
import { cookies } from "next/headers";
import { runWithAmplifyServerContext } from "@/amplifyServerUtils";
import { getCurrentUser } from "aws-amplify/auth/server";
export const getAuthData = async () => {
const authData = await runWithAmplifyServerContext({
nextServerContext: { cookies },
operation: (contextSpec) => getCurrentUser(contextSpec),
});
console.log("authData", authData);
return authData;
};
// page.tsx
"use client";
import { getAuthData } from "./actions";
export default function GetCurrentUser() {
const onClick = async () => {
const authData = await getAuthData();
console.log("authData", authData);
};
return (
<div>
<button onClick={onClick}>Click me</button>
</div>
);
}
This code is mostly based on Amplify Docs.
Don't forget to first set up authentication as described here.
Bonus: How I debugged AmplifyServerContextError
When I first wrote this code I got this error:
⨯ ../node_modules/@aws-amplify/core/dist/esm/adapterCore/serverContext/serverContext.mjs (31:10) @ getAmplifyServerContext ⨯ AmplifyServerContextError: Attempted to get the Amplify Server Context that may have been destroyed.
I still don't know what's causing this but the solution is to drop the '@' from the import declaration:
// This throws an error
import { getCurrentUser } from "@aws-amplify/auth/server";
// This works
import { getCurrentUser } from "aws-amplify/auth/server";