To add Auth to my Astro application, I used the package "auth-astro". Which provides auth.js for Astro. There is currently also a pull request which merges the "auth-astro" package into auth.js.
Adding the package
To add the package, you can use the astro cli like this.
If you are using pnpm you also need to install the cookie package:
pnpm i cookie
or install the needed packages manually:
Configuration
To configure the package, you need to edit the astro config called "astro.config.mjs" in the root of your project. As you can see in the example below (line 14 to 21), you need to add the auth function to the integrations array. You also need to add the auth provider you want to use. In this example I used Google. You can find more providers here.
Setup Environment Variables
To setup the environment variables, you need to create a ".env" file in the root of your project and add the following variables:
for the AUTH_SECRET you can use the following command to generate a random secret or use this site https://randomkeygen.com/
Creating the login page
Here is an example of a login page:
Check if a user is logged in
To check if the user is logged in, you can use the following code:
If the user is not logged in, he will be redirected to the login page using the Astros redirect utility function. You can find more information about the redirect function here.import BlogPostHeader from "@/components/blog/blog-post-header";