# Global Guard (https://s3.dimah.dev/docs/server/hooks/global-guard)



`guard` is defined on `dimahS3()` and executes on every incoming request prior to route resolution or plugin execution.

Use it for system-wide checks like user authentication, IP filtering, or tenant context.

```ts title="lib/s3.ts"
import { S3Client } from "@aws-sdk/client-s3";
import { dimahS3, errors, route } from "@dimah-s3/server";

export const awsS3 = new S3Client({/* env */});

export const s3 = dimahS3({
  client: awsS3,
  bucket: process.env.S3_BUCKET!,
  guard: async ({ request }) => {
    const session = await getSession(request);
    if (!session) throw errors.unauthorized();
  },
  routes: {
    avatar: route({
      upload: {
        fileTypes: ["image/*"],
        maxFileSize: 2 * 1024 * 1024,
      },
    }),
  },
});
```

***

## Guard context [#guard-context]

The global guard receives the raw `request` object. Route name and target key are resolved later in the lifecycle.

```ts
import type { GuardContext, RouteGuardContext } from "@dimah-s3/server";
```

<AutoTypeTable path="packages/server/src/types/hook-contexts.ts" name="GuardContext" />

## Frequently asked questions [#frequently-asked-questions]

<Accordions>
  <Accordion title="When should I use route.guard instead of global guard?">
    If your application has public routes (e.g. public media upload) and protected routes (e.g. private invoices), leave the global `guard` empty and apply `guard` on specific routes:

    ```ts
    export const s3 = dimahS3({
      routes: {
        publicMedia: route({
          upload: true,
        }),
        avatar: route({
          guard: requireUserSession,
          upload: true,
        }),
      },
    });
    ```
  </Accordion>

  <Accordion title="How do I attach custom headers from client requests?">
    On the client, pass headers in `createS3Client`:

    ```ts
    export const s3Client = createS3Client({
      headers: async () => ({
        Authorization: `Bearer ${await getToken()}`,
      }),
    });
    ```
  </Accordion>
</Accordions>
