Skip to main content
Docs

Locals

Through Astro locals, Clerk's Auth and current User 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 here.

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>

locals.currentUser()

Current user data is important for data enrichment. The currentUser() local fetch the current user's Backend User 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 reference.

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