Auth.js requires a secret to be set in order to sign the session cookie. This secret should be set to a random string of 32 characters. The documentation suggests on Linux, you generate one using openssl rand -hex 32, or you can navigate to generate-secret.vercel.app to generate one in the browser.
For non-vercel deployments, you’ll need to set the AUTH_TRUST_HOST environment variable to true.
Now that we’ve configured Auth.js, we need to allow our users to sign in & out. Open src/pages/index.astro and add the following code. This will render a sign in button if the user is not signed in, and a sign out button if they are. We get the session object from the Auth component, and use it to determine which button to render.
Now that we’ve got a sign in flow, we can add a protected route. Create a new file at src/pages/protected.astro. We want to only allow signed in users to access this page, so we’ll use the getSession server method to get the session object. If the user is not signed in, we’ll redirect them to the home page.
Add a link to the protected page in src/pages/index.astro to test it out:
With the new version of auth-astro we’ve made it easier than ever to add authentication to your Astro site with as little effort as possible. If you have any questions, feel free to reach out to me on Discord or Twitter, or report any issues on GitHub.