DEV Community

Cover image for Angular + Sanity CMS: Setting Up Your Sanity CMS Project with TypeScript

Angular + Sanity CMS: Setting Up Your Sanity CMS Project with TypeScript

Part 2: Setting Up Your Sanity CMS Project with TypeScript

Hey there, Angular devs! Welcome back to our Angular + Sanity CMS adventure. In Part 1, we introduced Sanity CMS, Portable Text, and the @limitless-angular/sanity library I released. We set up our Angular app to render Portable Text content like a pro. Now, it's time to dive into the Sanity side of things!

In this second part, we're going to create and configure a Sanity project that'll be the backend for our Angular app. We'll cover:

  1. Setting up a new Sanity project
  2. Defining our content schema using TypeScript
  3. Creating and managing content in Sanity Studio
  4. Getting our Sanity project to play nice with our Angular app

By the end of this tutorial, you'll have a fully functional content management system powering your Angular application. Let's dive in! 🏊‍♂️

What to Expect from Sanity

Before we get our hands dirty, let's break down what Sanity brings to the table:

  1. Sanity Studio: This is your content management dashboard. We'll run it locally during development, but it can be easily deployed for production use.

  2. Schema as Code: You'll be defining your content models (schemas) with TypeScript. These definitions automatically generate the input fields in Sanity Studio.

  3. API-first Approach: Sanity provides APIs to fetch your content, which we'll use with our Angular app.

Alright, let's get coding!

Step 1: Create a New Sanity Project

Let's create a new Sanity project using the following command:

npm create sanity@latest
Enter fullscreen mode Exit fullscreen mode

Now, follow the prompts to set up your project:

  1. "Create new project" and give it a cool name (I when with my-awesome-sanity-project because thy not?).
  2. Use the default dataset configuration.
  3. Select the project output path (hitting Enter works just fine).
  4. For the project template, go for "Blog (schema)" - it's perfect for our needs.
  5. When it asks about TypeScript, give it a resounding "Yes!"
  6. Pick your favorite package manager (npm, yarn, or pnpm).

The CLI will then set up your project with the chosen configuration. Once complete, you'll see instructions on how to start your Sanity Studio, and we'll modify the basic blog schema in the subsequent steps.

Step 2: Navigate to Your Project Directory

Once the project is created, navigate to its directory:

cd my-awesome-sanity-project
Enter fullscreen mode Exit fullscreen mode

Step 3: Define Your Schema

Now for the fun part - let's modify the blog post schema. Open the file schemaTypes/post.ts and update it with this TypeScript code:

import { defineField, defineType } from 'sanity';

export default defineType({
  name: 'post',
  title: 'Post',
  type: 'document',
  fields: [
    defineField({
      name: 'title',
      title: 'Title',
      type: 'string',
    }),
    defineField({
      name: 'slug',
      title: 'Slug',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96,
      },
    }),
    defineField({
      name: 'content',
      title: 'Content',
      type: 'array',
      of: [{ type: 'block' }],
    }),
  ],
});
Enter fullscreen mode Exit fullscreen mode

This schema defines a simple but powerful blog post document type with a title, slug, and content field that uses Portable Text.

Step 4: Start Sanity Studio

Time to see the fruits of our labor. Run this command:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Navigate to http://localhost:3333 in your browser to see the Sanity Studio interface. Go ahead, create a new "Post" document and let your creativity flow in the Portable Text editor.

Screenshot showing the sanity app running

Pretty good, right? This is where the magic happens. You can see how easy it is to create structured content with Sanity's editor.

Step 5: Configure CORS for Your Angular App

Before we can connect our Angular app to Sanity, we need to configure CORS (Cross-Origin Resource Sharing) to allow requests from our Angular app's URL. Here's how to do it:

  1. Go to https://www.sanity.io/manage and sign in to your account.
  2. Find your project in the list (hopefully you remember what you named it 😉).
  3. Look for "API" in the sidebar, then click on "CORS origins".
  4. Click the "Add CORS origin" button.
  5. For the "Origin" field, enter the URL where your Angular app will be hosted. During development, this is typically http://localhost:4200.
  6. There's a checkbox for "Allow credentials" - leave it alone for now, we're keeping things simple.
  7. Click "Save" to add the new CORS origin.

Screenshot of the Sanity management interface showing the CORS configuration page with the new origin added

This step ensures that your Angular app can make requests to your Sanity project's API.

Step 6: Get Your Project Details

To connect your Angular app to your Sanity project, you'll need your project ID and dataset name. You can find these in the sanity.config.ts file in your project root:

import { defineConfig } from 'sanity'

export default defineConfig({
  name: 'default',
  title: 'Your Awesome Project Name',

  projectId: 'your-project-id',
  dataset: 'production',

  // ... other configuration
});
Enter fullscreen mode Exit fullscreen mode

This is your project's unique identifier and the name of your dataset. You'll need these for the next step, so keep them handy!

Step 7: Update Your Angular App

Now that your Sanity project is all set up and looking good, let's update the sanity-client.ts file in your Angular project with your actual project details:

import { createClient } from '@sanity/client'

export const client = createClient({
  projectId: 'your-actual-project-id',
  dataset: 'production',
  useCdn: true,
  apiVersion: '2023-05-03', // Use today's date in YYYY-MM-DD format
});
Enter fullscreen mode Exit fullscreen mode

Don't forget to replace 'my-first-blog-post' with an actual slug from your Sanity project.

portableTextContent = toSignal(
  this.contentService.getPortableTextContent('my-first-blog-post')
);
Enter fullscreen mode Exit fullscreen mode

Wrapping Up: Bringing Angular and Sanity Together

Congratulations! You've just completed an exciting journey through Angular and Sanity CMS. Let's take a moment to reflect on what we've accomplished and where you can go from here:

  1. An Angular frontend that leverages the latest features, such as standalone components, signals, and the new control flow syntax.
  2. A flexible Sanity CMS backend, complete with a custom schema and improved Studio experience.

Key Takeaways

  • Sanity's Improvements: Sanity brings a streamlined setup process and an enhanced Studio experience.
  • TypeScript All the Way: From Angular to Sanity, we've used TypeScript throughout, ensuring type safety and improving developer experience.
  • Seamless Integration: The @limitless-angular/sanity library makes it surprisingly easy to bridge the gap between Angular and Sanity.

Final Thoughts

The combination of Angular and Sanity CMS gives you a solid foundation for building content-rich, dynamically updated web applications. Whether you're creating a blog, a portfolio, or a complex web app, you now have the tools to manage your content effortlessly and display it beautifully.

Happy coding, and may your content always be structured and your components forever standalone! 🚀✨

Top comments (0)