auth-astro

repository·main·Indexed 18 days ago

https://github.com/nowaythatworked/auth-astro

An Astro integration that wraps Auth.js to provide authentication for Astro projects. It automatically manages endpoints and session handling, offering pre-built SignIn and SignOut components, server-side session retrieval via getSession, and client-side authentication scripts. Requires Node.js >= 17.4, SSR enabled, and Astro output mode set to 'server'.

Tokens
3.3K
Snippets
18
Records
19
Agent score
53%

What's inside auth-astro

  1. Install auth-astro

    main

    You can install auth-astro using the Astro CLI, which automatically handles package installation and integration configuration, or manually.

    npm run astro add auth-astro

    Manual Installation

    Install the core packages:

    npm install auth-astro@latest @auth/core@^0.18.6

    Note for pnpm users: You must also install the cookie package:

    pnpm i cookie

    After manual installation, you must add the integration to your astro.config.mjs by importing it and adding it to the integrations array.

  2. Set up environment variables for auth-astro

    main

    To secure your authentication, you must set the following environment variables:

    1. AUTH_SECRET: A random 32-character hex string. You can generate one using openssl rand -hex 32.
    2. AUTH_TRUST_HOST: Set this to true if you are hosting on providers like Cloudflare Pages or Netlify.

    Note: If you are deploying to Vercel, you do not need to set AUTH_TRUST_HOST as the package detects the Vercel environment automatically.

    AUTH_SECRET=<auth-secret>
    AUTH_TRUST_HOST=true
  3. Configure auth-astro

    main

    Create an auth.config.ts file in your project root to define your authentication providers using the defineConfig helper.

    import GitHub from '@auth/core/providers/github'
    import { defineConfig } from 'auth-astro'
    
    export default defineConfig({
    	providers: [
    		GitHub({
    			clientId: import.meta.env.GITHUB_CLIENT_ID,
    			clientSecret: import.meta.env.GITHUB_CLIENT_SECRET,
    		}),
    	],
    })

    Callback URLs

    OAuth providers require a callback URL. By default, this is: [origin]/api/auth/callback/[provider]

    Example for GitHub: http://localhost:4321/api/auth/callback/github

    import GitHub from '@auth/core/providers/github'
    import { defineConfig } from 'auth-astro'
    
    export default defineConfig({
    	providers: [
    		GitHub({
    			clientId: import.meta.env.GITHUB_CLIENT_ID,
    			clientSecret: import.meta.env.GITHUB_CLIENT_SECRET,
    		}),
    	],
    })
  4. Install and configure the auth-astro integration

    main

    To use auth-astro in your Astro project, import the default integration export and add it to your astro.config.mjs file. You can also use the defineConfig helper exported from the package to ensure type safety for your Astro configuration.

    import { defineConfig } from 'astro/config';
    import authAstro from 'auth-astro';
    
    export default defineConfig({
      integrations: [authAstro()],
    });
    import authAstro from 'auth-astro';
    
    // In your astro.config.mjs
    export default {
      integrations: [authAstro()],
    };
  5. Set up the Auth.js API route handler in Astro

    main

    To enable authentication endpoints (like sign-in, sign-out, and callback handling) in your Astro project, you must create an API route handler using AstroAuth().

    This file should be placed at src/api/[...auth].ts (or .js). You must set export const prerender = false; to ensure the route is handled dynamically at runtime rather than being generated at build time. The AstroAuth() function returns the required GET and POST handlers for the Auth.js protocol.

    import { AstroAuth } from '../../server'
    
    export const prerender = false
    
    export const { GET, POST } = AstroAuth()
  6. Sign in and Sign out with client-side scripts

    main

    For client-side interactivity (e.g., inside a <script> tag), you can dynamically import signIn and signOut from auth-astro/client.

    <button id="login">Login</button>
    <button id="logout">Logout</button>
    
    <script>
      const { signIn, signOut } = await import("auth-astro/client")
      document.querySelector("#login").onclick = () => signIn("github")
      document.querySelector("#logout").onclick = () => signOut()
    </script>
  7. Sign in and Sign out with Astro Components

    main

    Use the pre-built SignIn and SignOut components from auth-astro/components within your Astro component scripts.

    ---
    import { SignIn, SignOut } from 'auth-astro/components'
    ---
    <SignIn provider="github" />
    <SignOut />
  8. Fetch the session on the server

    main

    To retrieve the current user's session within an Astro component's frontmatter (server-side), use the getSession method from auth-astro/server and pass the Astro.request object.

    ---
    import { getSession } from 'auth-astro/server';
    
    const session = await getSession(Astro.request)
    ---
    {session ? (
      <p>Welcome {session.user?.name}</p>
    ) : (
      <p>Not logged in</p>
    )}
  9. Fetch the session using the Auth component

    main

    The Auth component allows you to fetch the session and render UI based on the session state using a render prop. This is useful for conditional rendering of login/logout buttons.

    ---
    import type { Session } from '@auth/core/types';
    import { Auth, SignIn, SignOut } from 'auth-astro/components';
    ---
    <Auth>
      {(session: Session) => 
        {
          return (
            <>
              {session ? <SignOut>Logout</SignOut> : <SignIn provider="github">Login</SignIn>}
              <p>
                {session ? `Logged in as ${session.user?.name}` : 'Not logged in'}
              </p>
            </>
          )
        }
      }
    </Auth>
  10. Use defineConfig for type-safe configuration

    main

    The auth-astro package exports defineConfig which can be used to provide type safety when defining your Astro configuration. This is typically used in conjunction with the auth-astro integration to ensure all configuration properties are correctly typed.

    import { defineConfig } from 'astro/config';
    import authAstro from 'auth-astro';
    
    export default defineConfig({
      integrations: [authAstro()],
    });