View a markdown version of this page

Server-side rendering - AWS Amplify

Server-side rendering

To read the signed-in user in route handlers and loaders, call createServerAuth from @aws-amplifygen3/auth-js/server with your publishable key. It reads the session from the request’s cookies.

A deployed app uses token mode because its backend is on another host. In token mode, the session stays in the browser by default. The local backend runs on your page’s host, so the app uses cookie mode, and your server code reads the backend’s cookie. For the two modes, see User sessions.

Read the user in server code

In token mode, your server code finds no session, even when the browser shows the user as signed in. It’s the most common cause of a server-rendered page with no user. To fix it, keep the session in a cookie, as in the following Next.js steps.

  1. In browser code, create the client with sessionStore: 'cookie'. The SDK then keeps the session in the cookie __Host-<storageKey>.session on your app’s host.

    export const backend = createClient(process.env.AMPLIFY_BACKEND_URL!, process.env.AMPLIFY_BACKEND_PUBLISHABLE_KEY!, { auth: { sessionStore: 'cookie' }, })

    Browser code gets these two values only when the build inlines them, such as with the env setting in next.config.ts. For more information, see the client SDK README on GitHub.

  2. In server code, create a server auth client with your publishable key, and read the session. Without the key, createServerAuth fails.

    import { cookies } from 'next/headers' import { createServerAuth } from '@aws-amplifygen3/auth-js/server' const auth = createServerAuth({ baseUrl: `${process.env.AMPLIFY_BACKEND_URL}/auth`, // same backend URL as the browser client publishableKey: process.env.AMPLIFY_BACKEND_PUBLISHABLE_KEY!, // required cookies: await cookies(), }) const { data } = await auth.getSession() // or auth.getUser()

In cookie mode, the SDK ignores sessionStore and keeps the session in the backend’s own cookie. The local backend runs on your app’s host, so that cookie also reaches your server, and the same code works. In cookie mode, createServerAuth doesn’t call setCookies.

Write cookies back from middleware

Reading the session in server code can extend or end it, and change its cookies. To write those cookies onto your response, pass setCookies to createServerAuth. It gets cookies with name, value, and options, and a cookie with an empty value and maxAge: 0 removes that cookie. A React Server Component can’t set cookies, so do this in your proxy file. From Next.js 16, that file is proxy.ts and its function is proxy. On Next.js 15, name the file middleware.ts and the function middleware.

Don’t rely on this file to decide access. Check the user in the server code that reads your data. For more information, see Keep authorization out of middleware.

Write the cookies only on responses to page loads. Give the proxy a config.matcher that leaves out background requests, such as fetches and the requests that client-side navigation and prefetching make. If you write the cookies on the response to a background request, and the user signed in or out in the meantime, the browser gets the old session back.

A server framework without a cookie API can send serializeCookie(cookie) from @aws-amplifygen3/auth-js/server as a Set-Cookie header.

Sign users in from server code

To sign a user in from a server action or route handler, post the email and password to <backend URL>/auth/sign-in/email, and copy the backend’s session cookie onto your response. Send the publishable key in the apikey header, or the call fails with 401 invalid_credential. createServerAuth reads that cookie on later requests.

When you copy the cookie, follow these rules. If you don’t, the user appears signed out on the next page:

  • Take the name from the response. It’s amplifygen3.session_token on the local backend and __Host-amplifygen3.session_token on a deployed backend. With advanced.crossSubDomainCookies, a deployed backend uses __Secure-amplifygen3.session_token, because a __Host- cookie can’t carry a Domain.

  • Take the cookie that has a value. To clear older copies, a deployed backend also sends copies with empty values.

  • Decode the value. It arrives percent-encoded, and framework setters, such as Next.js cookies().set, encode it again.

  • Set it HTTP-only, with Path=/, SameSite=Lax, Secure for a __Host- or __Secure- name, and the response’s Max-Age.

Things to know about server sessions

  • The cookie’s name comes from the client’s storage key. Create both clients with the same backend URL, or pass the same storageKey to both.

  • A large session is split across the cookies __Host-<storageKey>.session.0, .1 and so on. The SDK reads and writes them together.

  • On an http: host other than localhost, and in Safari on http://localhost, the cookie has no __Host- prefix. To read it, pass secureCookies: false to createServerAuth and getSessionCookie. They then read only the cookie without the prefix.

  • getSessionCookie(request, { baseUrl }) returns the session token that the cookie holds, or null, for a quick check that a session exists. Pass it the same baseUrl, storageKey and secureCookies as createServerAuth. It doesn’t validate the session. Before you allow access, call getUser.

Errors

Error When What to do

createServerAuth requires the branch's publishableKey.

No publishableKey

Pass it

INVALID_EMAIL_OR_PASSWORD

Wrong email or password on a server sign-in

Show a sign-in error

403 INVALID_ORIGIN

Server code sends an untrusted Origin

Send a trusted one. See Auth configuration.

403 MISSING_OR_NULL_ORIGIN

Server code posts to /auth/sign-out with the session cookie and no Origin

Send a trusted Origin