Skip to content

reactive/data-client / .agents/skills/data-client-setup

data-client-setup

Verified

Install and set up @data-client/react or @data-client/vue in a project. Detects project type (NextJS, Expo, React Native, Vue, plain React) and protocol (REST, GraphQL, custom), then follows the bundled protocol-specific setup guide.

FileKindSize
SKILL.mdskill md13.9 KB
evals/evals.jsonconfig12.6 KB
references.jsonconfig523 B
references/DataClientPlugin.mdmarkdown6.6 KB
references/DataProvider.mdmarkdown6.6 KB
references/data-client-endpoint-setup.mdmarkdown8.5 KB
references/data-client-endpoint-setup/references/Endpoint.mdmarkdown20.9 KB
references/data-client-endpoint-setup/references/Endpoint.vue.mdmarkdown20.5 KB
references/data-client-graphql-setup.mdmarkdown4.8 KB
references/data-client-graphql-setup/references/auth.mdmarkdown1.9 KB
references/data-client-rest-setup.mdmarkdown7.6 KB
references/data-client-rest-setup/references/RestEndpoint.mdmarkdown45.2 KB
references/data-client-rest-setup/references/RestEndpoint.vue.mdmarkdown46.1 KB
references/data-client-rest-setup/references/auth.mdmarkdown9.4 KB
references/data-client-rest-setup/references/auth.vue.mdmarkdown9.7 KB
references/data-client-rest-setup/references/axios-migration.mdmarkdown25.4 KB
references/data-client-rest-setup/references/axios-migration.vue.mdmarkdown25.5 KB
references/data-client-rest-setup/references/django.mdmarkdown2.3 KB
references/data-client-rest-setup/references/fetch-migration.mdmarkdown4.0 KB
references/data-client-rest-setup/references/got-migration.mdmarkdown4.5 KB
references/data-client-rest-setup/references/hookifyResource.mdmarkdown6.0 KB
references/data-client-rest-setup/references/hookifyResource.vue.mdmarkdown6.3 KB
references/data-client-rest-setup/references/ky-migration.mdmarkdown3.9 KB
references/data-client-rest-setup/references/resource.mdmarkdown27.0 KB
references/data-client-rest-setup/references/resource.vue.mdmarkdown27.1 KB
references/data-client-rest-setup/references/superagent-migration.mdmarkdown4.1 KB
references/getDefaultManagers.mdmarkdown6.1 KB
references/getDefaultManagers.vue.mdmarkdown3.8 KB
references/installation.mdmarkdown4.0 KB
references/installation.vue.mdmarkdown2.7 KB
references/tanstack-query-migration.mdmarkdown31.1 KB

references/data-client-rest-setup/references/auth.vue.md

View on GitHub
<!-- Generated by `yarn build:skills` from docs/rest/guides/auth.md (vue). Edit the source doc, not this file. -->

# Rest Authentication

All network requests are run through the [getRequestInit](./RestEndpoint.vue.md#getRequestInit) optionally
defined in your [RestEndpoint](./RestEndpoint.vue.md).

## Cookie Auth (credentials)

Here's an example using simple [cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) auth by sending [fetch credentials](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#sending_a_request_with_credentials_included):

```ts title="AuthdEndpoint" {9}
import { RestEndpoint, type RestGenerics } from '@data-client/rest';

export default class AuthdEndpoint<
  O extends RestGenerics = any,
> extends RestEndpoint<O> {
  async getRequestInit(body: any): Promise<RequestInit> {
    return {
      ...(await super.getRequestInit(body)),
      credentials: 'same-origin',
    };
  }
}
```

```ts title="MyResource"
import { resource, Entity } from '@data-client/rest';
import AuthdEndpoint from './AuthdEndpoint';

class MyEntity extends Entity {
  id = '';
  title = '';
}

export const MyResource = resource({
  path: '/my/:id',
  schema: MyEntity,
  Endpoint: AuthdEndpoint,
});
```

```ts title="Usage" column
import { MyResource } from './MyResource';
MyResource.get({ id: 1 });
```

See [Django Integration](./django.md) for an example that also includes [CSRF protection](https://docs.djangoproject.com/en/5.0/howto/csrf/#using-csrf-protection-with-ajax).

## Access Tokens or JWT

**static member**

```ts title="login"
export const login = async (data: FormData) =>
  (
    await fetch('/login', { method: 'POST', body: data })
  ).json() as Promise<{
    accessToken: string;
  }>;
```

```ts title="AuthdEndpoint" {7,15,22}
import { RestEndpoint, type RestGenerics } from '@data-client/rest';
import { login } from './login';

export default class AuthdEndpoint<
  O extends RestGenerics = any,
> extends RestEndpoint<O> {
  declare static accessToken?: string;

  getHeaders(headers: HeadersInit) {
    // TypeScript doesn't infer properly
    const EP = this.constructor as typeof AuthdEndpoint;
    if (!EP.accessToken) return headers;
    return {
      ...headers,
      'Access-Token': EP.accessToken,
    };
  }
}

export const handleLogin = async e => {
  const { accessToken } = await login(new FormData(e.target));
  AuthdEndpoint.accessToken = accessToken;
};
```

```html title="Auth.vue"
<script setup lang="ts">
  import { handleLogin } from './AuthdEndpoint';
  import AuthForm from './AuthForm.vue';
</script>

<template>
  <AuthForm @submit="handleLogin" />
</template>
```

```ts title="MyResource"
import { resource, Entity } from '@data-client/rest';
import AuthdEndpoint from './AuthdEndpoint';

class MyEntity extends Entity {
  id = '';
  title = '';
}

export const MyResource = resource({
  path: '/my/:id',
  schema: MyEntity,
  Endpoint: AuthdEndpoint,
});
```

```ts title="Usage" column
import { MyResource } from './MyResource';
MyResource.get({ id: 1 });
```

**async function**

```ts title="login"
export const login = async (data: FormData) =>
  (
    await fetch('/login', { method: 'POST', body: data })
  ).json() as Promise<{
    accessToken: string;
  }>;

let token = '';
// imagine this used an async API like indexedDB
export const getAuthToken = async () => token;
export const setAuthToken = (accessToken: string) => {
  token = accessToken;
};
```

```ts title="AuthdEndpoint" {10,17}
import { RestEndpoint, type RestGenerics } from '@data-client/rest';
import { getAuthToken, setAuthToken, login } from './login';

export default class AuthdEndpoint<
  O extends RestGenerics = any,
> extends RestEndpoint<O> {
  async getHeaders(headers: HeadersInit) {
    return {
      ...headers,
      'Access-Token': await getAuthToken(),
    };
  }
}

export const handleLogin = async e => {
  const { accessToken } = await login(new FormData(e.target));
  setAuthToken(accessToken);
};
```

```html title="Auth.vue"
<script setup lang="ts">
  import { handleLogin } from './AuthdEndpoint';
  import AuthForm from './AuthForm.vue';
</script>

<template>
  <AuthForm @submit="handleLogin" />
</template>
```

```ts title="MyResource"
import { resource, Entity } from '@data-client/rest';
import AuthdEndpoint from './AuthdEndpoint';

class MyEntity extends Entity {
  id = '';
  title = '';
  pk() {
    return this.id;
  }
}

export const MyResource = resource({
  path: '/my/:id',
  schema: MyEntity,
  Endpoint: AuthdEndpoint,
});
```

```ts title="Usage" column
import { MyResource } from './MyResource';
MyResource.get({ id: 1 });
```

**function singleton**

```ts title="login"
export const login = async (data: FormData) =>
  (
    await fetch('/login', { method: 'POST', body: data })
  ).json() as Promise<{
    accessToken: string;
  }>;

let token = '';
export const getAuthToken = () => token;
export const setAuthToken = (accessToken: string) => {
  token = accessToken;
};
```

```ts title="AuthdEndpoint" {10,17}
import { RestEndpoint, type RestGenerics } from '@data-client/rest';
import { getAuthToken, setAuthToken, login } from './login';

export default class AuthdEndpoint<
  O extends RestGenerics = any,
> extends RestEndpoint<O> {
  getHeaders(headers: HeadersInit) {
    return {
      ...headers,
      'Access-Token': getAuthToken(),
    };
  }
}

export const handleLogin = async e => {
  const { accessToken } = await login(new FormData(e.target));
  setAuthToken(accessToken);
};
```

```html title="Auth.vue"
<script setup lang="ts">
  import { handleLogin } from './AuthdEndpoint';
  import AuthForm from './AuthForm.vue';
</script>

<template>
  <AuthForm @submit="handleLogin" />
</template>
```

```ts title="MyResource"
import { resource, Entity } from '@data-client/rest';
import AuthdEndpoint from './AuthdEndpoint';

class MyEntity extends Entity {
  id = '';
  title = '';
  pk() {
    return this.id;
  }
}

export const MyResource = resource({
  path: '/my/:id',
  schema: MyEntity,
  Endpoint: AuthdEndpoint,
});
```

```ts title="Usage" column
import { MyResource } from './MyResource';
MyResource.get({ id: 1 });
```

## Auth Headers from provide/inject {#auth-headers-from-react-context}

> **Warning**
>
> Using provide/inject for state that is not displayed (like auth tokens) is not recommended.
> This will result in unnecessary re-renders and application complexity.

**Resource**

We can transform any [Resource](./resource.vue.md) into one that uses composables to create endpoints
by using [hookifyResource](./hookifyResource.vue.md)

```ts title="resources/Post.ts"
import { inject } from 'vue';
import { resource, hookifyResource } from '@data-client/rest';

// Post defined here

export const AuthKey = Symbol('accessToken');

export const PostResource = hookifyResource(
  resource({ path: '/posts/:id', schema: Post }),
  function useInit(): RequestInit {
    const accessToken = inject(AuthKey, '');
    return {
      headers: {
        'Access-Token': accessToken,
      },
    };
  },
);
```

Then we can get the endpoints as composables in our Vue Components

```html title="PostDetail.vue"
<script setup lang="ts">
  import { useSuspense } from '@data-client/vue';
  import { PostResource } from 'resources/Post';

  const props = defineProps<{ id: string }>();
  const post = await useSuspense(PostResource.useGet(), () => ({
    id: props.id,
  }));
</script>

<template>
  <div>{{ post.title }}</div>
</template>
```

> **Warning**
>
> Using this means all endpoint calls must only occur at the top level of `<script setup>`.
>
> ```html title="CreatePost.vue"
> <script setup lang="ts">
>   import { useController } from '@data-client/vue';
>   import { PostResource } from 'resources/Post';
>
>   const controller = useController();
>   const createPost = PostResource.useGetList().push;
>   const onSubmit = (e: Event) =>
>     controller.fetch(createPost, {}, new FormData(e.target as HTMLFormElement));
> </script>
>
> <template>
>   <form @submit="onSubmit">
>     <!-- ... -->
>   </form>
> </template>
> ```

**RestEndpoint**

We will first provide an easy way of using the context to alter the fetch headers.

```ts title="api/AuthdEndpoint.ts"
import { RestEndpoint, type RestGenerics } from '@data-client/rest';

export default class AuthdEndpoint<
  O extends RestGenerics = any,
> extends RestEndpoint<O> {
  declare accessToken?: string;

  getHeaders(headers: HeadersInit): HeadersInit {
    return {
      ...headers,
      'Access-Token': this.accessToken,
    };
  }
}
```

Next we will [extend](./RestEndpoint.vue.md#extend) to generate a new endpoint with this context injected.

```ts
import { inject } from 'vue';

function useEndpoint(endpoint: RestEndpoint) {
  const accessToken = inject(AuthKey, '');
  return endpoint.extend({ accessToken });
}
```

> **Warning**
>
> Using this means all endpoint calls must only occur at the top level of `<script setup>`.
>
> ```html title="CreatePost.vue"
> <script setup lang="ts">
>   import { useController } from '@data-client/vue';
>   import { PostResource } from 'resources/Post';
>   import { useEndpoint } from './useEndpoint';
>
>   const controller = useController();
>   const createPost = useEndpoint(PostResource.getList.push);
>   const onSubmit = (e: Event) =>
>     controller.fetch(createPost, {}, new FormData(e.target as HTMLFormElement));
> </script>
>
> <template>
>   <form @submit="onSubmit">
>     <!-- ... -->
>   </form>
> </template>
> ```

## Code organization

If much of your `Resources` share a similar auth mechanism, you might
try extending from a base class that defines such common customizations.

## 401 Logout Handling

In case a users authorization expires, the server will typically responsd to indicate
as such. The standard way of doing this is with a 401. [LogoutManager](https://dataclient.io/vue/api/LogoutManager)
can be used to easily trigger any de-authorization cleanup.
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 197kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall