Astro.locals.auth() returns an Auth object. This JavaScript object contains important information like session data, your user's ID, as well as the ID of the Active Organization. Learn more about the Auth object hereClerk Icon.
---if (Astro.request.method ==='POST') {if (!Astro.locals.auth().isAuthenticated) {thrownewError('You must be signed in to add an item to your cart') }constdata=awaitAstro.request.formData()console.log('add item action', data)}---<formmethod="POST"> <inputvalue="test"type="text"name="name" /> <buttontype="submit">Add to Cart</button></form>
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.
exportconstGET:APIRoute= ({ locals }) => {// Use `locals.auth()` to protect a route based on token typeconstauthObject=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`) }returnnewResponse(JSON.stringify({}))}
The Backend UserClerk Icon object includes a privateMetadata field that should not be exposed to the frontend. Avoid passing the full user object returned by currentUser() to the frontend. Instead, pass only the specified fields you need.
src/pages/form.astro
---if (Astro.request.method ==='POST') {constuser=awaitAstro.locals.currentUser()if (!user) {thrownewError('You must be signed in to use this feature') }constdata=awaitAstro.request.formData()constserverData= { usersHobby:data.get('hobby'), userId:user.id, profileImage:user.imageUrl, }console.log('add item action completed with user details ', serverData)}---<formmethod="POST"> <inputvalue="soccer"type="text"name="hobby" /> <buttontype="submit">Submit your hobby</button></form>