Skip to main content
Docs

Locals

Through Astro locals, Clerk's and current objects can be accessed between middlewares and pages. These locals are injected when you configure the provided middleware.

locals.auth()

Astro.locals.auth() returns an Auth object. This JavaScript object contains important information like session data, your user's ID, as well as their active organization ID. Learn more about the Auth object .

locals.auth() options

  • Name
    opts?
    Type
    {acceptsToken: TokenType, treatPendingAsSignedOut: boolean }
    Description

    An optional object that can be used to configure the behavior of the locals.auth() function. It accepts the following properties:

    • acceptsToken?: The type of authentication token(s) to accept. Valid values are:

      • 'session_token' - authenticates a user session.
      • 'oauth_token' - authenticates a machine request using OAuth.
      • 'm2m_token' - authenticates a machine to machine request.
      • 'api_key' - authenticates a machine request using API keys.

      Can be set to:

      • A single token type.
      • An array of token types.
      • 'any' to accept all available token types.

      Defaults to 'session_token'.

    • treatPendingAsSignedOut?: A boolean that indicates whether to treat as signed out. Defaults to true.

Example: Protect a page or form

You can use the auth() local to protect your pages and forms. It will return the current user's ID if they are signed in, or null if they are not.

src/pages/protected.astro
---
const { userId, redirectToSignIn } = Astro.locals.auth()

if (!userId) {
  return redirectToSignIn()
}
---

<div>Protected page</div>
src/pages/form.astro
---
if (Astro.request.method === 'POST') {
  if (!Astro.locals.auth().userId) {
    throw new Error('You must be signed in to add an item to your cart')
  }

  const data = await Astro.request.formData()
  console.log('add item action', data)
}
---

<form method="POST">
  <input value="test" type="text" name="name" />
  <button type="submit">Add to Cart</button>
</form>

Example: Protect a route based on token type

The following example uses locals.auth() to protect the route based on token type:

  • It accepts any token type (acceptsToken: 'any') from the request.
  • If the token is a session_token, it logs that the request is from a user session.
  • Otherwise, it logs that the request uses a machine token and specifies its type.
export const GET: APIRoute = ({ locals }) => {
  // Use `locals.auth()` to protect a route based on token type
  const authObject = locals.auth({ acceptsToken: 'any' })

  if (authObject.tokenType === 'session_token') {
    console.log('This is a session token from a user')
  } else {
    console.log(`This is a ${authObject.tokenType} token`)
  }

  return new Response(JSON.stringify({}))
}

locals.currentUser()

Current user data is important for data enrichment. The currentUser() local fetch the current user's object, which includes all of the user's information and provides a set of methods to manage their account.

Under the hood, this local:

For more information on currentUser(), see the .

src/pages/form.astro
---
if (Astro.request.method === 'POST') {
  const user = await Astro.locals.currentUser()

  if (!user) {
    throw new Error('You must be signed in to use this feature')
  }

  const data = await Astro.request.formData()
  const serverData = {
    usersHobby: data.get('hobby'),
    userId: user.id,
    profileImage: user.imageUrl,
  }

  console.log('add item action completed with user details ', serverData)
}
---

<form method="POST">
  <input value="soccer" type="text" name="hobby" />
  <button type="submit">Submit your hobby</button>
</form>

Feedback

What did you think of this content?

Last updated on