> To build or manage a Wix site with an AI agent, follow https://www.wix.com/headless/skill.md
> It builds a new Wix site or puts your own site online, from a prompt, and keeps changing it afterwards. The pages are code in any web technology, and Wix runs the backend.
> It works through the Wix plugin (the Wix MCP and the Wix skills), the Wix CLI or no Wix login, and puts the site live on Wix hosting or on another host.
> Business features include a store, bookings, events and tickets, a restaurant, a blog, forms, members and many more.
> Read the Wix skills online at https://www.wix.com/skills
> 
> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - If a reference page seems to be missing its schema (parameters, return types, or type definitions), append `?schema=true` to its `.md` URL (e.g. `https://dev.wix.com/docs/contexts/contexts/stores/category-info/use-category-info-context.md?schema=true`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

## Resource: Tutorial | Create a “Top Blog Posts” Dashboard Page With the CLI

## Article: Tutorial | Create a “Top Blog Posts” Dashboard Page With the CLI

## Article Link: https://dev.wix.com/docs/build-apps/get-started/tutorials/tutorial-create-a-top-blog-posts-dashboard-page-with-the-cli.md

## Article Content:

# Tutorial | Create a Top Blog Posts App Using the Wix CLI

This tutorial demonstrates how to use the [Wix CLI](https://dev.wix.com/docs/wix-cli/cli-for-apps/about-the-wix-cli-for-apps.md) to build a Top Blog Posts app on the [Wix Platform](https://dev.wix.com/docs/build-apps/get-started/overview/the-wix-ecosystem.md). The app contains a dashboard page that shows the most-viewed and most-liked posts of a Wix site's blog in two cards.

By following this tutorial, you'll learn how to:

- Build a dashboard page using the [Wix Design System](https://www.wixdesignsystem.com/).
- Query blog posts and retrieve per-post metrics using the [Wix Blog SDK](https://dev.wix.com/docs/api-reference/business-solutions/blog/introduction?apiView=SDK.md).
- Navigate to a built-in Wix dashboard page from within your app, using the [Wix Dashboard SDK](https://dev.wix.com/docs/sdk/host-modules/dashboard/introduction.md).

The end result will look like this:

![App preview](https://wixmp-833713b177cebf373f611808.wixmp.com/images/eace32400be38d0fabb96420f0bb3177.png)

We'll use the following steps to build the Top Blog Posts app:

1. [Initialize the app](#step-1--initialize-the-app).
1. [Create the dashboard page](#step-2--create-the-dashboard-page).
1. [Run a local development server](#step-3--run-a-local-development-server).
1. [Add permissions](#step-4--add-permissions).
1. [Set up Wix Blog](#step-5--set-up-wix-blog).
1. [Develop the app](#step-6--develop-the-app).
1. [Display the top posts in the dashboard](#step-7--display-the-top-posts-in-the-dashboard).
1. [Test the app](#step-8--test-the-app).
1. [Build and deploy the app](#step-9--build-and-deploy-the-app).

## Before you begin

Before getting started, make sure that:

- You install [Node.js](https://nodejs.org/en/download/) (v24.22.1 or higher).
- You install [npm](https://www.npmjs.com/package/npm) or [yarn](https://www.npmjs.com/package/yarn).
- You're logged into your Wix Studio account. If you don't already have one, [sign up for a Wix Studio account](https://manage.wix.com/account/custom-apps).

## Step 1 | Initialize the app

We use the Wix CLI to initialize our Top Blog Posts app. In the process of initializing our app, the Wix CLI automatically:

- Creates a new app in the [Custom Apps page](https://manage.wix.com/account/custom-apps) of your Wix Studio workspace.
- Sets up a new folder for your app in your local file system. The folder includes:
  - A `src` folder containing initial boilerplate code for an app with a dashboard page.
  - A `package.json` file containing your app dependencies.
- Creates a local Git repository for your app.

To initialize the app:

1. Open a terminal and navigate to the folder where you want to create your app.
2. Run the following command:

    ```bash
    npm create @wix/new@latest app
    ```

    If prompted to install the `@wix/create-new` package, press `y`.
3. Select **Create a new Wix app**.
4. Select **Create a basic app**.
5. Enter a name for your app. Let’s name our app `Top Blog Posts`.
6. Press `Enter` to accept the default folder name (`top-blog-posts`).
7. When asked to configure Wix MCP for your IDE, select your preferred MCP.

    A green **Success** message confirms that your app has been registered in the [Custom Apps page](https://manage.wix.com/account/custom-apps).

8. Press `Enter` to accept the default namespace (`top-blog-posts`).
9. Press `Enter` to accept the default code identifier (`top_blog_posts`).

You now have a new app in the [Custom Apps page](https://manage.wix.com/account/custom-apps), a new folder in your local file system, and a local Git repository for developing and testing your app.

## Step 2 | Create the dashboard page

We use the CLI's `generate` command to create a dashboard page for our app.

To create the dashboard page:

1. Navigate to your newly created folder for your app.

    ```bash
    cd top-blog-posts
    ```

2. Run the following command and follow the prompts:

    ```bash
    wix app generate
    ```

3. When prompted for the kind of extension, select **Dashboard Page**.

4. When prompted for a page title, enter **Top Blog Posts**.

5. When prompted for the page route, press `Enter` to accept the default (`top-blog-posts`).

Upon completion, the extension files are created at `src/extensions/dashboard/pages/top-blog-posts/`:

```bash
src
└── extensions
    └── dashboard
        └── pages
            └── top-blog-posts
                ├── top-blog-posts.extension.ts
                └── top-blog-posts.tsx
```

For more information about these files, see [Dashboard Page Extension Files and Code](https://dev.wix.com/docs/build-apps/develop-your-app/develop-an-app-with-the-cli/supported-extensions/dashboard/dashboard-pages/dashboard-page-extension-files-and-code.md).

<blockquote class="tip">

**Tip:** The CLI's default scaffold also created a `my-page` extension at `src/extensions/dashboard/pages/my-page/`. You can leave it (it won't interfere with this tutorial) or delete the `my-page/` folder to keep the dashboard sidebar showing only the **Top Blog Posts** page.

</blockquote>

## Step 3 | Run a local development server

Now that you’ve initialized your app, you can run a local development server to see the app in action, and view local changes as you develop your app.

To run a local development server for your app:

1. In the terminal, from your app's folder, run the following command:

    ```bash
    wix app dev
    ```

1. The first time you run the command, the CLI tells you that you don't have a development site configured. Press `Enter` to open the app installation page in your default browser. If the browser doesn't open, [install your app on your test site](https://dev.wix.com/docs/build-apps/launch-your-app/app-distribution/test-your-app-on-a-premium-site.md) manually, and then run `wix app dev` again.

1. In the **Select a development site** dialog, select the development site you'll use throughout this tutorial to run and test your app. To create a new one, click **Create Dev Site**. The newly created development site is automatically named **Dev Sitex** followed by a number, such as **Dev Sitex 12345**, and appears in your Wix account's list of sites.

1. Click **Test App** to install your app on your development site.

1. In the terminal, click the **Dashboard** link to open your development site's dashboard.

1. In the dashboard sidebar, click **Apps > Top Blog Posts** to see your newly created app’s dashboard page. We add the content of our app’s dashboard page in the next step.

The page shows a header and an empty state.

Your app is now running on your development site. As you develop your app, any changes made to your app’s code are reflected in real time on your development site.

If your changes don’t show up, try refreshing the page, or closing and reopening the development site.

## Step 4 | Add permissions

In this step, we'll add permissions for the app. Every SDK API requires specific permissions to use. In this app, we will use the [`queryPosts()`](https://dev.wix.com/docs/api-reference/business-solutions/blog/posts-stats/query-posts?apiView=SDK.md) and [`getPostMetrics()`](https://dev.wix.com/docs/api-reference/business-solutions/blog/posts-stats/get-post-metrics?apiView=SDK.md) functions in the [Wix Blog API](https://dev.wix.com/docs/api-reference/business-solutions/blog/introduction?apiView=SDK.md) to get a list of posts and retrieve their metrics.

To use these functions, we need to give our app permission requirements in the app dashboard. Once we do this, anyone installing the app will be prompted to grant the specified permissions.

Both `queryPosts()` and `getPostMetrics()` require the same scope: a read blog scope. Each method's reference page (linked above) lists the exact scope it requires in its **Permission Scopes** section, including the scope's ID (`SCOPE.DC-BLOG.READ-BLOGS`).

To add the scope:

1. Go to the [**Permissions** tab](https://manage.wix.com/app-selector?title=Select+an+App&primaryButtonText=Select+Site&actionUrl=https%3A%2F%2Fdev.wix.com%2Fapps%2F%7BappId%7D%2Fdev-center-permissions) in your app's dashboard.
1. Click **Add Permissions**.
1. Search for the scope. Several scopes can have similar names, so match the one whose ID matches the scope ID shown on the method's reference page.
1. Check its checkbox under **Choose Permission Scopes** and click **Save**.

For more information on configuring permissions, see [Configure permissions for your app](https://dev.wix.com/docs/build-apps/develop-your-app/access/authorization/configure-permissions-for-your-app.md).

## Step 5 | Set up Wix Blog

Before you can start coding, you need to set up Wix Blog on your site and app:

1. Install the [Wix Blog](https://www.wix.com/app-market/wix-blog?searchLocation=home) app on your test site. You can create some new blog posts, or use the sample ones provided by Wix.
1. Publish the site and “like” one of the posts. You can find the blog at `https://{your-site-url}/blog`.
1. Open your app’s dashboard in the [Custom Apps page](https://manage.wix.com/account/custom-apps).
1. Click **Test App**, then select **Test on dev site**. In the **Select a development site** dialog, choose your dev site and click **Test App**. The app is reinstalled on your dev site with the latest permissions.

## Step 6 | Develop the app

Next, we will use the JavaScript SDK to retrieve blog data from the test site.

### Create a code file for your SDK code

Before starting to write code for the SDK, set up a file for your code. The code for this project uses the SDK's [`blog`](https://dev.wix.com/docs/api-reference/business-solutions/blog/introduction?apiView=SDK.md) and [`dashboard`](https://dev.wix.com/docs/sdk/host-modules/dashboard/introduction.md) modules. The `dashboard` module is preinstalled by the CLI, but you'll need to install the `blog` module manually.

1. Create a file named `blog-utils.js` at `src/extensions/dashboard/pages/top-blog-posts/`, alongside the `top-blog-posts.tsx` file you generated in Step 2.
1. In your IDE terminal, run the following command:

    ```bash
    npm install @wix/blog
    ```

### Retrieve blog data

Next, use the blog module in the SDK to retrieve the data you need.

1. Import the `posts` submodule from the `@wix/blog` package into your file.
1. Create an `async` function called `getTopBlogPosts`.
1. Use the [`queryPosts()`](https://dev.wix.com/docs/api-reference/business-solutions/blog/posts-stats/query-posts?apiView=SDK.md) function to find the posts with the most likes and views. The query allows you to sort the posts in descending order based on likes and views. Call this function twice, once for likes and once for views.
1. Extract the first item IDs from the result and save them as `mostLiked` and `mostViewed` variables.
1. Use the [`getPostMetrics()`](https://dev.wix.com/docs/api-reference/business-solutions/blog/posts-stats/get-post-metrics?apiView=SDK.md) function to retrieve the post metrics by passing the ID of the post. These metrics include likes and views. Save these metrics as `mostLikedMetrics` and `mostViewedMetrics` variables.
1. Your function should return an object with two keys, `mostViewed` and `mostLiked`. The value for each key should be an object containing the post data and the likes and views respectively of the highest-ranking posts.


Your final `blog-utils.js` file should look like this:

```js
import { posts } from '@wix/blog';

export async function getTopBlogPosts() {
  const mostLikedPosts = await posts.queryPosts().descending('metrics.likes').find();
  const mostViewedPosts = await posts.queryPosts().descending('metrics.views').find();


  const mostLiked = mostLikedPosts.items[0];
  const mostViewed = mostViewedPosts.items[0];

  const mostLikedMetrics =  await posts.getPostMetrics(mostLiked._id);
  const mostViewedMetrics =  await posts.getPostMetrics(mostViewed._id)

  return {
    mostViewed: {
      post: mostViewed,
      views: mostViewedMetrics.metrics.views ?? 0,
    },
    mostLiked: {
      post: mostLiked,
      likes: mostLikedMetrics.metrics.likes ?? 0,
    },
  };
}
```

## Step 7 | Display the top posts in the dashboard

Now that we have the blog data, we can use the [Wix Design System](https://www.wix-pages.com/design-system-documentation/#/page/introduction/about) to display it on a dashboard page. The app framework created by the CLI includes the code for a sample dashboard page. We can use that code as the basis for a dashboard page.

### Set up the dashboard code files

1. Open the `top-blog-posts.tsx` file at `src/extensions/dashboard/pages/top-blog-posts/`.
1. Delete all the import statements and paste in the following ones:

    ```tsx
    import { Button, Card, Heading, Text, Page, WixDesignSystemProvider, Box, Loader } from "@wix/design-system";
    import "@wix/design-system/styles.global.css";
    import * as Icons from "@wix/wix-ui-icons-common";
    import React, { useEffect, useState } from "react";
    import { dashboard } from "@wix/dashboard";
    import { getTopBlogPosts } from './blog-utils';
    import { posts } from '@wix/blog';
    ```

1. Replace the generated `DashboardPage` component and its `export` statement with an empty `Index()` component that returns only a `<WixDesignSystemProvider>` element.

When you’re done, your file should look like this:

```tsx
import {
  Button,
  Card,
  Heading,
  Text,
  Page,
  WixDesignSystemProvider,
  Box,
  Loader,
} from "@wix/design-system";
import "@wix/design-system/styles.global.css";
import * as Icons from "@wix/wix-ui-icons-common";
import React, { useEffect, useState } from "react";
import { dashboard } from "@wix/dashboard";
import { getTopBlogPosts } from './blog-utils';
import { posts } from '@wix/blog';

export default function Index() {
  return <WixDesignSystemProvider></WixDesignSystemProvider>;
}
```

### Prepare blog data for display

Next, get your blog data ready to display on your dashboard page. This code goes below the import statements on your `top-blog-posts.tsx` file:

1. Define the interfaces for viewed and liked blog posts.

   ```js
   interface ViewedBlogPost {
     post: posts.Post;
     views: number;
   }
   interface LikedBlogPost {
     post: posts.Post;
     likes: number;
   }
   ```

1. In the `Index()` component use React hooks to access the data.

   ```ts
   const [mostViewed, setMostViewed] = useState<ViewedBlogPost | null>(null);
   const [mostLiked, setMostLiked] = useState<LikedBlogPost | null>(null);
   const [mostViewedPublishedDate, setMostViewedPublishedDate] = useState<string | null>(null);
   const [mostLikedPublishedDate, setMostLikedPublishedDate] = useState<string | null>(null);
   useEffect(() => {
     async function fetchBlogPosts() {
       try {
         const { mostViewed, mostLiked } = await getTopBlogPosts();
         setMostViewed(mostViewed);
         setMostLiked(mostLiked);
         setMostViewedPublishedDate(
           mostViewed.post.lastPublishedDate
             ? new Date(mostViewed.post.lastPublishedDate).toDateString()
             : null
         );
         setMostLikedPublishedDate(
           mostLiked.post.lastPublishedDate
             ? new Date(mostLiked.post.lastPublishedDate).toDateString()
             : null
         );
       } catch (error) {
         console.log("Failed to fetch blog post data.", error);
       }
     }
     fetchBlogPosts();
   }, []);
   ```

1. Add a loader that displays while data are loading.

   ```js
   if (!mostViewed || !mostLiked) {
     return (
       <Box align="center" verticalAlign="middle">
         <Loader text="Loading..." />
       </Box>
     );
   }
   ```

### Create the page structure

Next, add React components from the [Wix Design System](https://www.wix-pages.com/design-system-documentation/#/page/introduction/about) to create the page structure.

1. Add nested components between the `<WixDesignSystemProvider>` tags in the return statement for the `Index()` component. Structure your components to match the following diagram. Wrap `<Text>` components in `<div>` tags so that they each display on a different line.

![Outline boxes](https://wixmp-833713b177cebf373f611808.wixmp.com/images/7c1fb8d7942d8c0dc4ddd2eaf9309da7.png)

1. Add the following variables to the opening tag of the `Box` component to ensure the cards inside it display correctly:

```js
gap="5px" direction="vertical"
```

When you’re done, your `Index()` component should look like this:

```js
export default function Index() {
  return (
    <WixDesignSystemProvider>
      <Page>
        <Page.Header />
        <Page.Content>
          <Box gap="5px" direction="vertical">
            <Card>
              <Card.Header />
              <Card.Divider />
              <Card.Content>
                <Heading> </Heading>
                <Text> </Text>
                <div>
                  <Text> </Text>
                </div>
                <div>
                  <Text> </Text>
                </div>
              </Card.Content>
            </Card>
            <Card>
              <Card.Header />
              <Card.Divider />
              <Card.Content>
                <Heading> </Heading>
                <Text> </Text>
                <div>
                  <Text> </Text>
                </div>
                <div>
                  <Text> </Text>
                </div>
              </Card.Content>
            </Card>
          </Box>
        </Page.Content>
      </Page>
    </WixDesignSystemProvider>
  );
}
```

### Add content to the page

Add static text, dynamic text, and other content to your Design System components. In some cases, text is added between the component’s opening and closing tags. In other cases, the text is passed into the component as a variable.

1. Pass these variables to the `Heading` components inside the `Card.Header` components:

   ```js
   size="medium" as="h2"
   ```

1. Pass these variables to the `Heading` components inside the `Car.Content` components:

   ```js
   size="small" as="h3"
   ```

1. Add an `onClick` event handler to the `Button` component in the page header actions bar. Set the variable to this function:

   ```js
   () => dashboard.navigate('social-blog').
   ```

When you’re done, your `Index()` function should look like this:

```js
export default function Index() {
  return (
    <WixDesignSystemProvider>
      <Page>
        <Page.Header
          title="Top Blog Posts"
          subtitle="These are the top blog posts on your site."
          actionsBar={
            <Button
              prefixIcon={<Icons.Edit />}
              onClick={() => dashboard.navigate("social-blog")}
            >
              Edit Your Blog
            </Button>
          }
        />
        <Page.Content>
          <Box gap="5px" direction="vertical">
            <Card>
              <Card.Header
                title={
                  <Heading size="medium" as="h2">
                    Most Viewed
                  </Heading>
                }
              />
              <Card.Divider />
              <Card.Content>
                <Heading size="small" as="h3">
                  Title: {mostViewed.post.title}
                </Heading>
                <Text>Excerpt: {mostViewed.post.excerpt}</Text>
                <div>
                  <Text>Last published: {mostViewedPublishedDate}</Text>
                </div>
                <div>
                  <Text>Views: {mostViewed.views}</Text>
                </div>
              </Card.Content>
            </Card>
            <Card>
              <Card.Header
                title={
                  <Heading size="medium" as="h2">
                    Most Liked
                  </Heading>
                }
              />
              <Card.Divider />
              <Card.Content>
                <Heading size="small" as="h3">
                  Title: {mostLiked.post.title}
                </Heading>
                <Text>Excerpt: {mostLiked.post.excerpt}</Text>
                <div>
                  <Text>Last published: {mostLikedPublishedDate}</Text>
                </div>
                <div>
                  <Text>Likes: {mostLiked.likes}</Text>
                </div>
              </Card.Content>
            </Card>
          </Box>
        </Page.Content>
      </Page>
    </WixDesignSystemProvider>
  );
}
```

## Step 8 | Test the app

Now that the app’s code is ready, you can test it locally using the Wix CLI.

The finished code sample should look like this:

```ts
import {
  Button,
  Card,
  Heading,
  Text,
  Page,
  WixDesignSystemProvider,
  Box,
  Loader,
} from "@wix/design-system";
import "@wix/design-system/styles.global.css";
import * as Icons from "@wix/wix-ui-icons-common";
import React, { useEffect, useState } from "react";
import { dashboard } from "@wix/dashboard";
import { getTopBlogPosts } from './blog-utils';
import { posts } from '@wix/blog';

interface ViewedBlogPost {
  post: posts.Post;
  views: number;
}
interface LikedBlogPost {
  post: posts.Post;
  likes: number;
}
export default function Index() {
  const [mostViewed, setMostViewed] = useState<ViewedBlogPost | null>(null);
  const [mostLiked, setMostLiked] = useState<LikedBlogPost | null>(null);
  const [mostViewedPublishedDate, setMostViewedPublishedDate] = useState<string | null>(null);
  const [mostLikedPublishedDate, setMostLikedPublishedDate] = useState<string | null>(null);
  useEffect(() => {
    async function fetchBlogPosts() {
      try {
        const { mostViewed, mostLiked } = await getTopBlogPosts();
        setMostViewed(mostViewed);
        setMostLiked(mostLiked);
        setMostViewedPublishedDate(
          mostViewed.post.lastPublishedDate
            ? new Date(mostViewed.post.lastPublishedDate).toDateString()
            : null
        );
        setMostLikedPublishedDate(
          mostLiked.post.lastPublishedDate
            ? new Date(mostLiked.post.lastPublishedDate).toDateString()
            : null
        );
      } catch (error) {
        console.log("Failed to fetch blog post data.", error);
      }
    }
    fetchBlogPosts();
  }, []);

  if (!mostViewed || !mostLiked) {
    return (
      <Box align="center" verticalAlign="middle">
        <Loader text="Loading..." />
      </Box>
    );
  }
  return (
    <WixDesignSystemProvider>
      <Page>
        <Page.Header
          title="Top Blog Posts"
          subtitle="These are the top blog posts on your site."
          actionsBar={
            <Button
              prefixIcon={<Icons.Edit />}
              onClick={() => dashboard.navigate("social-blog")}
            >
              Edit Your Blog
            </Button>
          }
        />
        <Page.Content>
          <Box gap="5px" direction="vertical">
            <Card>
              <Card.Header
                title={
                  <Heading size="medium" as="h2">
                    Most Viewed
                  </Heading>
                }
              />
              <Card.Divider />
              <Card.Content>
                <Heading size="small" as="h3">
                  Title: {mostViewed.post.title}
                </Heading>
                <Text>Excerpt: {mostViewed.post.excerpt}</Text>
                <div>
                  <Text>Last published: {mostViewedPublishedDate}</Text>
                </div>
                <div>
                  <Text>Views: {mostViewed.views}</Text>
                </div>
              </Card.Content>
            </Card>
            <Card>
              <Card.Header
                title={
                  <Heading size="medium" as="h2">
                    Most Liked
                  </Heading>
                }
              />
              <Card.Divider />
              <Card.Content>
                <Heading size="small" as="h3">
                  Title: {mostLiked.post.title}
                </Heading>
                <Text>Excerpt: {mostLiked.post.excerpt}</Text>
                <div>
                  <Text>Last published: {mostLikedPublishedDate}</Text>
                </div>
                <div>
                  <Text>Likes: {mostLiked.likes}</Text>
                </div>
              </Card.Content>
            </Card>
          </Box>
        </Page.Content>
      </Page>
    </WixDesignSystemProvider>
  );
}
```

To test your app, do the following:

1. Run a local development server for your app. Your app’s dashboard page will now look like this:
   ![App preview](https://wixmp-833713b177cebf373f611808.wixmp.com/images/eace32400be38d0fabb96420f0bb3177.png)
1. The page loads your most liked and most viewed posts automatically.
1. If things don’t look right, open your browser’s developer tools and check for errors in the console.

## Step 9 | Build and deploy the app

After testing your app and seeing that it works as expected, you can:

- [Create a public preview of your app](https://dev.wix.com/docs/build-apps/manage-your-app/versioning/about-app-versioning.md),
- [Build your app](https://dev.wix.com/docs/build-apps/launch-your-app/app-distribution/about-app-distribution.md)
- [Deploy your app](https://dev.wix.com/docs/build-apps/manage-your-app/versioning/release-a-new-app-version.md).