# Tutorial - Share a schema across projects

Follow a hands-on tutorial to share one schema across three Hygraph projects with the Hygraph CLI. Use the full schema in one project, a customized schema in another, and a partial schema in a third.

In this tutorial, you share one travel schema across three Hygraph projects, one per market. By the end, you will have one shared schema in code, three project configs that each use it differently, and three projects that you plan and apply with one command.

For how sharing a schema works, the rules, and best practices, see [Share a schema across projects](https://hygraph.com/docs/developer-guides/schema-as-code/hygraph-cli/share-schema-across-projects-cli).

## What you'll build

A travel site has three Hygraph projects, one per market, named Travel Americas, Travel Europe, and Travel Asia. They share a schema with `Destination` and `Offer` models, a `SeoMeta` component, and a `DestinationType` enumeration. English is the default locale in every project.

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

| Project | Target | How it uses the shared schema | Locales |
| --- | --- | --- | --- |
| Travel Americas | `americas` | Full. You export the shared schema from it. | English |
| Travel Europe | `europe` | Customized. It adds a `localTip` field, a `ski` destination type, and a `LocalGuide` model, and makes the SEO title required. | English, German |
| Travel Asia | `asia` | Partial. It leaves out the `Offer` model, and the `bestSeason` field of `Destination`. | English, Japanese |

Every project stays within the [Hobby plan limits](https://hygraph.com/docs/developer-guides/project/update-billing#hobby-plan), so you can follow the tutorial on any plan.

The finished files are in the [example repository](https://github.com/hygraph/hygraph-cli-share-schema-example). Use it to compare your files with the finished ones, or to start from a working setup.

## Step 1: Set up the three projects

1. [Clone the starter project: Travel Americas](https://app.hygraph.com/clone/af860c04543b4da0af0a3ee5c8c92702?name=Travel%20Americas%20-%20Schema%20CLI%20starter). 
2. [Create two empty projects](https://hygraph.com/docs/getting-started/quickstart#create-a-project), named `Travel Europe` and `Travel Asia`. Keep English as the default locale. Use new projects. If a project already has a schema, its plan deletes everything the config doesn't include, with its content.
3. In each project, go to **Project Settings > Access > Permanent Auth Tokens**, click **Generate CLI PAT**, and copy the token.
4. For each project, note the following. You need them in each project's target.
    - Project ID: **Project Settings > General > Project**
    - Management API endpoint: **Project Settings > Access > Endpoints > Management API**

## Step 2: Set up a folder

Create a folder for the tutorial, and install the Hygraph CLI in it:

```bash
mkdir travel-schema
cd travel-schema
npm init -y
npm i -D @hygraph/cli
```

## Step 3: Export Travel Americas as a config

1. `export` reads its token from `HYGRAPH_TOKEN`. 

      **macOS and Linux**

    ```bash
    export HYGRAPH_TOKEN="<americas-permanent-auth-token>"
    ```

      
      **Windows (PowerShell)**

    ```powershell
    $env:HYGRAPH_TOKEN="<americas-permanent-auth-token>"
    ```


2. Export the Travel Americas schema to a config file:

    ```bash
    npx hygraph export --name americas --out hygraph-americas.config.ts
    ```

    `export` reads the project, environment, and endpoint from the Travel Americas token.

    The CLI writes `hygraph-americas.config.ts`. Open it. It holds the whole schema, with `Destination`, `Offer`, `SeoMeta`, `DestinationType`, and the English locale, and a target named `americas`.

## Step 4: Move the shared schema into `schema.ts`

Every project will import the shared schema from one file. Move the definitions out of the exported config.

1. Create `schema.ts` in the same folder, with this content. These are the definitions you just exported, with the English locale and each group exported by name:

    ```ts
    import { define, system } from "@hygraph/cli/define";

    export const english = define.locale({ apiId: "en", displayName: "English", isDefault: true });

    const DestinationType = define.enumeration({
      apiId: "DestinationType",
      displayName: "Destination type",
      values: [
        { apiId: "beach", displayName: "Beach" },
        { apiId: "city", displayName: "City" },
        { apiId: "mountains", displayName: "Mountains" },
      ],
    });

    const SeoMeta = define.component({
      apiId: "SeoMeta",
      apiIdPlural: "SeoMetas",
      displayName: "SEO meta",
      fields: [
        define.field.singleLine({ apiId: "title", displayName: "Title", title: true, localized: true }),
        define.field.singleLine({ apiId: "description", displayName: "Description", localized: true }),
      ],
    });

    const Destination = define.model({
      apiId: "Destination",
      apiIdPlural: "Destinations",
      displayName: "Destination",
      fields: [
        define.field.singleLine({ apiId: "name", displayName: "Name", title: true }),
        define.field.singleLine({ apiId: "bestSeason", displayName: "Best season" }),
        define.field.enumeration({ apiId: "type", displayName: "Type", enumeration: DestinationType }),
        define.field.component({ apiId: "seo", displayName: "SEO", component: () => SeoMeta }),
      ],
    });

    const Offer = define.model({
      apiId: "Offer",
      apiIdPlural: "Offers",
      displayName: "Offer",
      fields: [
        define.field.singleLine({ apiId: "title", displayName: "Title", title: true, localized: true }),
        define.field.referenceOneWay({ apiId: "destination", displayName: "Destination", to: () => Destination }),
        define.field.component({ apiId: "seo", displayName: "SEO", component: () => SeoMeta }),
      ],
    });

    const Asset = system.model.asset({ fields: [] });
    const Query = system.model.query({ fields: [] });

    export const enumerations = { DestinationType };
    export const components = { SeoMeta };
    export const models = { Destination, Offer, Asset, Query };
    ```

2. Replace the contents of `hygraph-americas.config.ts` with this config. It builds the environment from `schema.ts`, and reads its token from `HYGRAPH_TOKEN_AMERICAS`. Set `project` and `endpoint` to your Travel Americas values. You can copy them from the exported file before you replace it:

    ```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: "americas",
      project: "<americas-project-id>",
      environment: "master",
      endpoint: "<americas-management-api-endpoint>",
      token: process.env.HYGRAPH_TOKEN_AMERICAS ?? "",
      apply: environment,
    });
    ```

3. Check that the move changed nothing. The target now reads `HYGRAPH_TOKEN_AMERICAS`, not `HYGRAPH_TOKEN`, so set it, then plan Travel Americas:

    **macOS and Linux**

    ```bash
    export HYGRAPH_TOKEN_AMERICAS="<americas-permanent-auth-token>"
    npx hygraph plan hygraph-americas.config.ts
    ```

    
    **Windows (PowerShell)**

    ```powershell
    $env:HYGRAPH_TOKEN_AMERICAS="<americas-permanent-auth-token>"
    npx hygraph plan hygraph-americas.config.ts
    ```


    The plan shows no changes, because Travel Americas already has this schema. If the plan lists changes, compare `schema.ts` with the exported config, and restore the definition that differs.

## Step 5: Create the Travel Europe config

Create `hygraph-europe.config.ts` with this content. Set `project` and `endpoint` to your Travel Europe values:

```ts
import { define, system } from "@hygraph/cli/define";
import * as shared from "./schema";

// Add a field to a shared model
const models = {
  ...shared.models,
  Destination: {
    ...shared.models.Destination,
    fields: [
      ...shared.models.Destination.fields,
      define.field.singleLine({ apiId: "localTip", displayName: "Local tip" }),
    ],
  },
};

// Add a value to a shared enumeration.
// renamedFrom: null is needed because the shared values already include it.
const enumerations = {
  ...shared.enumerations,
  DestinationType: {
    ...shared.enumerations.DestinationType,
    values: [
      ...shared.enumerations.DestinationType.values,
      { apiId: "ski", displayName: "Ski", renamedFrom: null },
    ],
  },
};

// Replace a field on a shared component
const components = {
  ...shared.components,
  SeoMeta: {
    ...shared.components.SeoMeta,
    fields: shared.components.SeoMeta.fields.map((field) =>
      field.apiId === "title"
        ? define.field.singleLine({ apiId: "title", displayName: "Title", title: true, localized: true, required: true })
        : field
    ),
  },
};

// Add a model only this project needs
const LocalGuide = define.model({
  apiId: "LocalGuide",
  apiIdPlural: "LocalGuides",
  displayName: "Local guide",
  fields: [
    define.field.singleLine({ apiId: "name", displayName: "Name", title: true }),
  ],
});

// Add the locale this market needs
const german = define.locale({ apiId: "de", displayName: "German" });

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

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

Notice how the config changes the shared schema without touching `schema.ts`. It copies the shared objects, adds a field, an enumeration value, and a model, replaces the SEO `title` field with a required one, and adds the German locale.

## Step 6: Create the Travel Asia config

Create `hygraph-asia.config.ts` with this content. Set `project` and `endpoint` to your Travel Asia values:

```ts
import { define, system } from "@hygraph/cli/define";
import * as shared from "./schema";

// Leave the Offer model out
const { Offer, ...sharedModels } = shared.models;

// Leave the bestSeason field out of Destination
const models = {
  ...sharedModels,
  Destination: {
    ...sharedModels.Destination,
    fields: sharedModels.Destination.fields.filter((field) => field.apiId !== "bestSeason"),
  },
};

// Add the locale this market needs
const japanese = define.locale({ apiId: "jp", displayName: "Japanese" });

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

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

This config leaves out the `Offer` model, and filters the `bestSeason` field out of `Destination`. It adds the Japanese locale.

## Step 7: Create `hygraph.config.ts`

In the same folder, create `hygraph.config.ts` with the list of project configs:

```ts
import americas from "./hygraph-americas.config.ts";
import europe from "./hygraph-europe.config.ts";
import asia from "./hygraph-asia.config.ts";

export default [americas, europe, asia];
```

## Step 8: Plan all three configs

1. The `americas`, `europe`, and `asia` targets read their own tokens. 

      **macOS and Linux**

    ```bash
    export HYGRAPH_TOKEN_AMERICAS="<americas-permanent-auth-token>"
    export HYGRAPH_TOKEN_EUROPE="<europe-permanent-auth-token>"
    export HYGRAPH_TOKEN_ASIA="<asia-permanent-auth-token>"
    ```

      
      **Windows (PowerShell)**

    ```powershell
    $env:HYGRAPH_TOKEN_AMERICAS="<americas-permanent-auth-token>"
    $env:HYGRAPH_TOKEN_EUROPE="<europe-permanent-auth-token>"
    $env:HYGRAPH_TOKEN_ASIA="<asia-permanent-auth-token>"
    ```


2. Plan each project:

    ```bash
    npx hygraph plan
    ```

The CLI shows one plan per project:

- `americas` shows no changes.
- `europe` creates the whole schema, because Travel Europe is empty. The plan includes the shared models, component, and enumeration, the `localTip` field, the `ski` value, the `LocalGuide` model, and the German locale.
- `asia` creates the shared schema without `Offer` and `bestSeason`, and the Japanese locale.

No plan shows a delete. Travel Europe and Travel Asia start empty, so there's nothing to delete.

## Step 9: Apply configs to projects

```bash
npx hygraph apply
```

The CLI shows the plans again, and asks you to confirm once for every project. Type `y`. Each project gets its own migration.

To check that everything was applied, run `npx hygraph plan` again. Every project shows no changes.

## Step 10: Verify the result in Studio

Open each project in Studio:

- `Travel Europe`: The schema has a `Local guide` model, and `Destination` has a `Local tip` field. The project lists `German` as an additional locale in **Project Settings > General > Locales**.
- `Travel Asia`: The schema has no `Offer` model, and `Destination` has no `Best season` field. The project lists `Japanese` as an additional locale in **Project Settings > General > Locales**.
- `Travel Americas`: No changes.

## What you learned

- **Export one project** to get its schema as code.
- **Move the shared definitions into `schema.ts`**, and import them in each project's config.
- **Use a full, customized, or partial schema**, depending on what each project needs.
- **Give each project its own token variable**, so each target reaches only its own project.
- **Plan and apply every project with one command**, with one migration per project.
