Properties

createAuthRouteHandlers: CreateAuthRouteHandlers

The factory function to create the route handlers for the Amplify server-side authentication. You can call this function and export the result as the route handlers in the Next.js API routes, to authenticate your end users on the server side.

Note: when enabling server-side authentication, Amplify APIs can no longer be used in the client-side.

Example

// In `src/amplifyUtils.ts`
import { createServerRunner } from 'aws-amplify/adapter-nextjs';
import outputs from '@/amplify_outputs.json';

export const { createAuthRouteHandlers } = createServerRunner({ config: outputs });

// In `src/app/api/auth/[slug]/route.tsx` (App router)
import { createAuthRouteHandlers } from '@/amplifyUtils';

export const GET = createAuthRouteHandlers({
redirectOnSignInComplete: "/home",
redirectOnSignOutComplete: "/sign-in",
);

// In `src/pages/api/auth/[slug].tsx` (Pages router)
import { createAuthRouteHandlers } from '@/amplifyUtils';

export default createAuthRouteHandlers({
redirectOnSignInComplete: "/home",
redirectOnSignOutComplete: "/sign-in",
});
runWithAmplifyServerContext: NextServer.RunOperationWithContext

The function to run an operation with the Amplify server context. The operation is a callback function that takes a context spec parameter which is used to call the Amplify-side server APIs. The result of the operation is returned as a promise.

Example

// In `src/amplifyUtils.ts`
import { createServerRunner } from 'aws-amplify/adapter-nextjs';
import outputs from '@/amplify_outputs.json';

export const { runWithAmplifyServerContext } = createServerRunner({ config: outputs });

// In `src/app/home/page.tsx` (App router)
import { cookies } from 'next/headers';
import { runWithAmplifyServerContext } from '@/amplifyUtils';

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

return <div>{`Hello, ${user.username}`}</div>;
}

// In `src/pages/home/index.tsx` (Pages router)
import { runWithAmplifyServerContext } from '@/amplifyUtils';

export const getServerSideProps = async ({ req, res }) => {
const user = await runWithAmplifyServerContext({
nextServerContext: { request: req, response: res },
operation: (contextSpec) => getCurrentUser(contextSpec),
});

return {
props: { user },
}
}

export default function HomePage(props) {
return <div>{`Hello, ${props.user.username}`}</div>;
}