🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js Protecting Routes and Signing In

Signing in gives the reader a session. The session opens /my-books, and the page greets the reader by name.

The sign-in providers

The check asks Auth.js for its providers. The credentials provider is listed.

curl -s http://localhost:3112/api/auth/providers

The demo account on the page

The sign-in page names the demo account. The check finds the email on the page.

curl -s http://localhost:3112/sign-in | grep -o 'ada@example.com'

Example

curl -s -b cookies.txt http://localhost:3112/my-books | grep -o 'Signed in as <!-- -->Ada'

Key points

  • Session: the record that says who is signed in, kept in a cookie
  • Auth.js checks the email and password. The demo account is ada@example.com with password books123.
  • The sign-in form calls the sign-in action. The action signs the reader in.
  • The /my-books page reads the session on the server. No session means a redirect to /sign-in.
  • A signed-in visit shows the books and the name. The page greets Ada.
  • Production needs AUTH_TRUST_HOST=true in .env.local. Without it, every session check fails.

In this example, the check visits /my-books with the signed-in cookie. The page answers with Signed in as Ada, so the session was read on the server and the reader is known. The cookie came from the sign-in flow: a token from /api/auth/csrf, a POST to the credentials callback with the demo account, and a 302 to /my-books. A wrong password is turned away with a 302 to the sign-in page with error=CredentialsSignin. The sign-in form itself could not be driven from curl here, so the form submit is still unverified.

Note

The demo users live in plain text in the app, for teaching only. A real app stores users in a database with hashed passwords.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

What does the /my-books page show a signed-in reader?