# Share schema across projects

Keep one shared schema in TypeScript and apply it to several Hygraph projects, such as one per brand or market, with project-specific additions and changes.

Keep one shared schema in code and apply it to several Hygraph projects, such as one project per brand or market. Each project can use the full schema, a customized schema, or a partial schema.

Every project inherits the shared schema, and can add, change, or leave out parts of it. A project gets changes to the shared schema only when you plan and apply its target. Until then, it keeps its current schema.

The [tutorial](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/tutorial-share-schema-across-projects-cli) walks through this setup with three travel projects, and the [example repository](https://github.com/hygraph/hygraph-cli-share-schema-example) has the finished files.

## How it works

![Share schema across projects](https://hygraph.com/images/docs/developer-guides/schema-as-code/share-schema-across-projects.svg)

The setup has three kinds of files:

| File | What it holds |
| --- | --- |
| `schema.ts` | The shared schema: models, components, enumerations, and the default locale. It has no target, so you can't run `plan` on it. |
| One config per project, such as `hygraph-a.config.ts`, `hygraph-b.config.ts`, and `hygraph-c.config.ts` | The project's environment, built from the shared schema with any changes and locales of its own, and the project's target. |
| `hygraph.config.ts` | The list of project configs. `plan` and `apply` run on every project in it, with one plan and one migration per project. |

There's no live link between projects. Editing `schema.ts` doesn't change any project by itself. A project gets the change only when you plan and apply its target. Until then, it keeps its current schema.

## Before you begin

- [Install the Hygraph CLI](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/get-started-cli#step-1-install-the-cli) in the folder where you'll keep the configs. You need version 0.0.13 or later, which reads the project and endpoint from the token.
- Have two or more Hygraph projects, with the same default locale. Each project should be new, or have a schema that already matches the shared schema.
- A [Permanent Auth Token](https://hygraph.com/docs/getting-started/access-and-permissions/api-access#authenticated-requests-permanent-auth-tokens) for each project. In each project's **Project Settings > Access > Permanent Auth Tokens**, click **Generate CLI PAT**.
- For each project, note the following. You need them in each project's target.
    - The project ID, from **Project Settings > General > Project** or your project URL: `https://app.hygraph.com/<project-id>/<environment>`.
    - The Management API endpoint, from **Project Settings > Access > Endpoints > Management API**.
- Check each project's [Hygraph plan limits](https://hygraph.com/docs/developer-guides/project/update-billing#commercial-limits), such as the number of locales, models, and components. Each project gets the whole shared schema, plus its own changes, so it must fit within its own plan.

**Warning:**
Each project's config describes that project's whole schema. When you plan a project that has models, fields, enumerations, or locales that its config doesn't include, the plan deletes them, with their content. `apply` stops on these deletes until you pass `--prune`. Review each project's plan before you apply.

## Set up a shared schema

1. Export one project, and give its target a name with `--name`. Every target needs a unique name, and without `--name`, every exported target is named after its environment, such as `master`. `export` reads the token from `HYGRAPH_TOKEN`, and the project, environment, and endpoint from the token:

      **macOS and Linux**

    ```bash
    export HYGRAPH_TOKEN="<project-a-permanent-auth-token>"
    npx hygraph export --name project-a --out hygraph-a.config.ts
    ```

      
      **Windows (PowerShell)**

    ```powershell
    $env:HYGRAPH_TOKEN="<project-a-permanent-auth-token>"
    npx hygraph export --name project-a --out hygraph-a.config.ts
    ```


2. Move the exported definitions into a shared file, `schema.ts`. See [Create the shared schema file](#create-the-shared-schema-file).
3. Create a config for each project. Build its environment from `schema.ts`, and point its target at the project. Give each target its own token variable, such as `process.env.HYGRAPH_TOKEN_A`. If every target read `HYGRAPH_TOKEN`, they would all send the same token, and only one project would accept it. For project A, replace the contents of the exported `hygraph-a.config.ts` with a config like this one:

    ```ts
    import { define, system } from "@hygraph/cli/define";
    import { components, english, enumerations, models } from "./schema";

    const environment = define.environment({
      locales: [english],
      stages: [system.stage.draft(), system.stage.published()],
      enumerations: Object.values(enumerations),
      components: Object.values(components),
      models: Object.values(models),
    });

    export default define.target({
      name: "project-a",
      project: "<project-a-id>",
      environment: "master",
      endpoint: "<project-a-management-api-endpoint>",
      token: process.env.HYGRAPH_TOKEN_A ?? "",
      apply: environment,
    });
    ```

    The other projects' configs import from `schema.ts` the same way, with their own target and token variable. A project with locales of its own, such as `german`, defines them in its config, and lists them after `english`.

4. List the project configs in `hygraph.config.ts`:

    ```ts
    import projectA from "./hygraph-a.config.ts";
    import projectB from "./hygraph-b.config.ts";
    import projectC from "./hygraph-c.config.ts";

    export default [projectA, projectB, projectC];
    ```

5. Set each project's token variable. `plan` and `apply` read these variables, not `HYGRAPH_TOKEN`.

      **macOS and Linux**

    ```bash
    export HYGRAPH_TOKEN_A="<project-a-permanent-auth-token>"
    export HYGRAPH_TOKEN_B="<project-b-permanent-auth-token>"
    export HYGRAPH_TOKEN_C="<project-c-permanent-auth-token>"
    ```

      
      **Windows (PowerShell)**

    ```powershell
    $env:HYGRAPH_TOKEN_A="<project-a-permanent-auth-token>"
    $env:HYGRAPH_TOKEN_B="<project-b-permanent-auth-token>"
    $env:HYGRAPH_TOKEN_C="<project-c-permanent-auth-token>"
    ```


6. Plan each project, and review each plan before you apply. If a plan deletes something you want to keep, such as a model or a locale, add it to that project's config and plan again:

    ```bash
    npx hygraph plan
    npx hygraph apply
    ```

## Create the shared schema file

`schema.ts` holds the definitions every project shares. You create it from the config you exported in [Set up a shared schema](#set-up-a-shared-schema), and move the definitions unchanged:

- Export the default locale by name, such as `english`. Leave the project's other locales in its config.
- Export the rest grouped by kind, as `enumerations`, `components`, and `models`.
- List the system models `Asset` and `Query` in `models` too. If your models have asset fields, the matching fields on `Asset` move with them.

You can create it with an AI coding agent, or manually.

### With an AI coding agent

An AI coding agent can move the definitions for you. For a large schema, it can also [split them into one file per model or component](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/use-cli-with-ai-agents#organize-a-large-config).

<blockquote className="bg-surface-1 border-primary rounded-3 my-6 border-l-8 [&>*:first-child]:mt-0 [&>*:last-child]:mb-0" style={{ padding: "1rem 1.25rem" }}>

**Example prompt**

1. Move every enumeration, component, and model in `hygraph-a.config.ts` into a new file, `schema.ts`, without changing them. Include system models, such as `system.model.asset`.
2. Move the default locale into `schema.ts`, and export it by name. Leave the other locales in `hygraph-a.config.ts`.
3. Export the rest grouped by kind, as `enumerations`, `components`, and `models`.
4. In `hygraph-a.config.ts`, keep the target, and build its environment from `schema.ts` with `Object.values`.
5. Run `npx hygraph plan hygraph-a.config.ts`, and show me the plan. It should show no changes.

</blockquote>

If the plan shows a change, the agent changed a definition while moving it. Ask it to compare the definition with the exported config, and to restore it.

### Manually

1. Create `schema.ts` next to `hygraph-a.config.ts`, and import `define` and `system` from `@hygraph/cli/define`.
2. Cut every `define.enumeration`, `define.component`, and `define.model` from `hygraph-a.config.ts`, and paste them into `schema.ts`. Move the system models, such as `system.model.asset`, too. Keep definitions that reference each other, such as `to: () => SharedModel`, in the same file.
3. Move the default locale out of `define.environment`, and export it by name, such as `export const english = define.locale({ ... })`. Leave the project's other locales in `hygraph-a.config.ts`.
4. At the end of `schema.ts`, export the definitions grouped by kind:

    ```ts
    export const enumerations = { SharedEnumeration };
    export const components = { SharedComponent };
    export const models = { SharedModel, Asset, Query };
    ```

5. In `hygraph-a.config.ts`, import from `schema.ts`, and build the environment with `Object.values`, as in the project A config in [Set up a shared schema](#set-up-a-shared-schema).
6. Run `npx hygraph plan hygraph-a.config.ts`. Project A already has this schema, so the plan should show no changes. If it shows changes, a definition changed during the move. Compare it with the exported config, and restore it.

When `schema.ts` is ready, go back to [Set up a shared schema](#set-up-a-shared-schema), and create a config for each project.

## Use the shared schema

Each project's config decides how the project uses the shared schema. The [tutorial](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/tutorial-share-schema-across-projects-cli) has a complete config for each.

**Warning:**
Leaving a shared model or field out of one project's config plans a delete in that project only. `schema.ts` and the other projects don't change. 

### Full schema

Build the environment from the shared objects directly, with no changes. This is the project A config in [Set up a shared schema](#set-up-a-shared-schema).

### Customized schema

Copy the shared objects into the project's config, and change the copy. `import * as shared` imports everything `schema.ts` exports as one object, such as `shared.models` and `shared.english`. In project B, this adds a field to `SharedModel`.

```ts
import * as shared from "./schema";

const models = {
  ...shared.models,
  SharedModel: {
    ...shared.models.SharedModel,
    fields: [
      ...shared.models.SharedModel.fields,
      define.field.singleLine({ apiId: "projectBField", displayName: "Project B field" }),
    ],
  },
};
```

`...shared.models` copies every shared model, and `SharedModel` replaces the shared one. Its `fields` array copies that model's shared fields and adds `projectBField`. The project's environment lists this `models` object, so the new field is part of project B's schema. `schema.ts` stays as it is.

To replace a shared field, map over the shared fields, and return your own definition for that field. In project B, this makes the `title` field of `SharedComponent` required:

```ts
const components = {
  ...shared.components,
  SharedComponent: {
    ...shared.components.SharedComponent,
    fields: shared.components.SharedComponent.fields.map((field) =>
      field.apiId === "title"
        ? define.field.singleLine({ apiId: "title", displayName: "Title", title: true, required: true })
        : field
    ),
  },
};
```

The new definition replaces the shared one completely. Keep the same `apiId`, so the plan updates the field instead of deleting it, and include every option you want to keep, such as `title: true`. The project's environment lists this `components` object.

### Partial schema

Build the environment without the parts you leave out. In project C, this leaves out a model, and one field of another.

```ts
import * as shared from "./schema";

const { LeftOutModel, ...sharedModels } = shared.models;

const models = {
  ...sharedModels,
  SharedModel: {
    ...sharedModels.SharedModel,
    fields: sharedModels.SharedModel.fields.filter((field) => field.apiId !== "leftOutField"),
  },
};

const environment = define.environment({
  locales: [shared.english],
  stages: [system.stage.draft(), system.stage.published()],
  enumerations: Object.values(shared.enumerations),
  components: Object.values(shared.components),
  models: Object.values(models),
});
```

`const { LeftOutModel, ...sharedModels }` takes `LeftOutModel` out of the shared models, and keeps every other model in `sharedModels`. 

`filter` keeps every field except `leftOutField`. `define.environment` then lists `Object.values(models)`. 

`models` is `sharedModels` and the filtered `SharedModel`, so `LeftOutModel` and `leftOutField` are not in this project's environment.

## Work with a shared schema

After you set up a shared schema, you can add projects to it, and move changes from projects into the shared schema.

### Add a project

To add a project later:

1. [Create the project in Studio](https://hygraph.com/docs/getting-started/quickstart#create-a-project).
2. In the project's **Project Settings > Access > Permanent Auth Tokens**, click **Generate CLI PAT**, and copy the token.
3. Create a config for the project, such as `hygraph-d.config.ts`. Build its environment from the shared schema, as a full, customized, or partial schema. In its target, set the new project's ID, and a token variable of its own, such as `HYGRAPH_TOKEN_D`.
4. Add its target to `hygraph.config.ts`.
5. Set the environment variables for any [remote source secrets](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/define-your-schema-in-code-cli#remote-sources-and-secrets). `export` never writes secret values, so the new project needs them.
6. Set the new project's token in its variable, then plan and apply the new target:

    ```bash
    npx hygraph plan --target <new-project-name>
    npx hygraph apply --target <new-project-name>
    ```

Watch for these differences in a new project:

- If its default locale differs from the config's, the plan refuses. The CLI can't change the default locale, so change it in Studio first.
- System components that apps create aren't in the config. Install the apps in the new project.
- If the new project is on a Hygraph plan with lower limits, such as fewer components, `apply` fails. See [Commercial limits](https://hygraph.com/docs/developer-guides/project/update-billing#commercial-limits).
- Fields the CLI can't read yet are [placeholders](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/define-your-schema-in-code-cli#fields-the-cli-cant-read) in the config. Create them in Studio.

To add an environment to a project you already manage, such as a new `staging` environment, see [Environments](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/define-your-schema-in-code-cli#environments).

### Move a project's change into the shared schema

When a change made for one project should apply to all of them, move it into `schema.ts`, and remove the copy from the project's config. If both define the same field, the plan for that project fails, because the field exists twice.

## Best practices

- **Keep the shared schema as the default.** Change the schema for one project only when the change is specific to that project. When two or more projects need the same change, move it into the shared schema.
- **Keep the `apiId`.** When you change a model, field, or value from the shared schema, keep its `apiId`. The plan matches elements by API ID, so a new API ID deletes the old element and its content, and creates a new one.
- **Rename in the shared schema with `renamedFrom`.** Every project then renames the element and keeps its content. See [Rename without losing content](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/define-your-schema-in-code-cli#rename-without-losing-content).
- **Leave out a model together with the fields that reference it.** If another model has a reference field to the model you leave out, the field points to a model that isn't in the environment, and `plan` rejects the config. Leave out that field too.
- **Replace a shared field only when you need to.** A replaced field replaces the shared one completely. An option you leave out falls back to its default, so include every option you want to keep, such as `title` or `validations`. The replacement no longer follows the shared schema. If you later add a character limit to that field in `schema.ts`, the other projects get the limit. The project with the replacement keeps its own field. If you rename or remove the field in `schema.ts`, the replacement stops applying. Check the project's plan whenever you change a field it replaces.
- **Define each field in one place only.** If a project's config and the shared schema both define the same field, the plan for that project fails. When you move a change into the shared schema, remove it from the project's config in the same change.
- **Keep one default locale in `schema.ts`.** Every project needs that same default locale, because the CLI can't change it. Add each project's other locales in its own config. Removing a locale from a project's config deletes that locale and its content.
- **Each project's Hygraph plan limits apply.** If a project's plan allows fewer models, components, or locales than its config defines, `apply` fails. For more information, see [Plan limits](https://hygraph.com/docs/developer-guides/project/update-billing#commercial-limits).
- **Plan every project after you change `schema.ts`.** A shared change reaches every project, and each project can react differently, such as a project that replaces the changed field. Run `npx hygraph plan` without `--target` before you merge.
- **Use one token per project, and apply in stages.** A token should only reach its own project. Apply changes to staging first, and to production after review. See [Run the Hygraph CLI in CI](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/run-cli-in-ci).
- **Explain each project-specific change.** Add a comment to every change in a project's config, so reviewers know why that project differs.
- **Lock the schema in Studio.** Turn on [Schema Lock](https://hygraph.com/docs/developer-guides/project/schema-lock) for each environment the configs manage, so a change in one project's Studio doesn't make it drift from the shared schema.
- **Change the shared schema and the project configs together.** Commit them in one change, so the plans you review match what you merge.

## Related docs

- [Tutorial: Share a travel schema across three markets](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/tutorial-share-schema-across-projects-cli): Set up a shared schema for three projects, step by step.
- [Define your schema in code](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/define-your-schema-in-code-cli): Learn the functions and options for models, fields, and enumerations.
- [Run the Hygraph CLI in CI](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/run-cli-in-ci): Plan and apply every project from a pipeline.
- [Hygraph CLI reference](https://hygraph.com/docs/api-reference/hygraph-cli/hygraph-cli-reference-overview): Look up every command, function, and option in the CLI.
