Post types

A post type decides what a post has: the built-in fields (title, slug, excerpt, tags and attachments, each required, optional or none) and your own fields, such as the version of a DevLog entry or whether a reply is the accepted answer. Each space picks a type for its posts (rootType) and the types its replies may use (replyTypes, with defaultReplyType for replies that don't choose). See Spaces and members for how a space uses them.

Defining types

Open your site in the console and choose Edit post types. The whole definition is one JSON document: edit it as text (with completion from the published JSON Schema at /schemas/post-types.json) or with the form. You can also have an AI write the JSON and paste it in. Every edit is checked before you apply it: the console shows the changes and any problems, each with a detailed English message you can copy back to the AI.

Your own fields have a key, a label, a kind and whether they are required:

  • text: A one-line string
  • longText: A string
  • number: A finite number
  • boolean: true or false
  • select: One of options
  • date: A YYYY-MM-DD string

A field can have a default. New posts get it, and existing posts that have no value return it.

Type names, field labels, options and defaults are returned to anyone by GET /v1/spaces, so don't put internal information in them.

Typing your code

In the console's Export section, download the .d.ts and add it to your project (any file the TypeScript project includes). It fills KnitTypeRegistry from @knit/core:

knit-post-types.d.ts
// Generated by Knit from your post types. Do not edit; download it again after changing the types.
import "@knit/core";

declare module "@knit/core" {
  interface KnitTypeRegistry {
    postTypes: {
      "devlog": {
        typeKey: "devlog";
        kind: "root";
        fields: {
          "version": string;
          "stage"?: "alpha" | "beta" | "stable";
        };
      };
      "reply": {
        typeKey: "reply";
        kind: "reply";
        fields: { [key in never]: never };
      };
      "answer": {
        typeKey: "answer";
        kind: "reply";
        fields: {
          "accepted"?: boolean;
        };
      };
    };
    spaces: {
      "dev-log": {
        root: KnitTypeRegistry["postTypes"]["devlog"];
        reply: KnitTypeRegistry["postTypes"]["reply"] | KnitTypeRegistry["postTypes"]["answer"];
        defaultReply: KnitTypeRegistry["postTypes"]["reply"];
      };
    };
  }
}

Without the file, everything still works: fields is Record<string, unknown> and any type key or space key is a string. With it, typeKey and space only accept your types and spaces, and fields follows each type. Download it again whenever you change the types or spaces in the console. Values you read from the API (space, typeKey) can still be keys that aren't in your .d.ts (a space or type added after you downloaded it), so they are typed as your keys or any other string; only what you send is limited to your keys.

The space decides the type, so you rarely need typeKey:

  • createPost and useKnitComposer need space for both root posts and replies. Without typeKey, a root post's fields follow the space's root type, and a reply's follow the space's default reply type. typeKey picks another reply type the space allows; for a root post, it can only be the root type.
  • updatePost<"devlog">(id, input) checks fields against the type you pass (a post keeps its type). Without it, fields can be the fields of any of your types.
  • listPosts({ rootId, typeKey }) returns posts whose fields have that type.
  • <Composer.Field<"devlog"> name="..." /> only accepts that type's field keys. Without the type argument, name is any string.
devlog-client.ts
import type { KnitClient } from "@knit/core";

// Every post you create names its space. The space decides the type, so `fields` is checked
// against it even without typeKey.
export async function publish(client: KnitClient) {
  // A root post uses the space's root type ("devlog").
  const { post } = await client.createPost({
    space: "dev-log",
    title: "1.2.0",
    body: "What changed",
    fields: { version: "1.2.0", stage: "beta" },
  });

  // A reply names the thread's space too. Without typeKey it uses the default reply type;
  // typeKey picks another reply type the space allows.
  await client.createPost({
    parentId: post.id,
    space: "dev-log",
    typeKey: "answer",
    body: "Fixed in 1.2.1",
    fields: { accepted: true },
  });

  // A post keeps its type. Pass the type key to check the fields you update.
  await client.updatePost<"devlog">(post.id, { fields: { stage: "stable" } });

  // Filtering a thread by typeKey gives posts whose fields have that type.
  const answers = await client.listPosts({ rootId: post.id, typeKey: "answer" });
  return answers.items.filter((item) => !item.isDeleted && item.fields.accepted);
}

Writing fields

The ready-made PostEditor doesn't draw your own fields by itself: their labels, layout and help text are yours to decide. Add them through PostEditor's children, or build the whole form with Composer's parts. Composer.Field draws one input that matches the field's kind (text → input, longText → textarea, number → number input, boolean → checkbox, select → select, date → date input), and draws nothing for a key the type doesn't have. Pass children to draw it yourself: it receives { field, value, setValue, disabled }.

devlog-editor.tsx
"use client";

import { Composer } from "@knit/react/primitives";

// The fields of the "devlog" type are your own, so the ready-made PostEditor doesn't show them.
// Build the form from Composer's parts and place each field where you want it.
// Composer.Field<"devlog"> checks `name` against the type's fields (a typo is a type error).
export function DevlogEditor() {
  return (
    <Composer.Root space="dev-log">
      <Composer.TitleInput placeholder="Title" />
      <label htmlFor="devlog-version">Version</label>
      <Composer.Field<"devlog"> id="devlog-version" name="version" placeholder="1.2.0" />
      <label htmlFor="devlog-stage">Stage</label>
      <Composer.Field<"devlog"> id="devlog-stage" name="stage" emptyOptionLabel="—" />
      <Composer.Editor placeholder="What changed?" />
      <Composer.Error />
      <Composer.Submit>Publish</Composer.Submit>
    </Composer.Root>
  );
}

To keep the ready-made PostEditor and add a field, pass it as children; it is drawn between the title and slug inputs and the body. To add it to the editor inside PostList and PostDetail, replace components.PostEditor.

post-editor-field.tsx
"use client";

import { KnitProvider } from "@knit/react";
import { Composer } from "@knit/react/primitives";
import { PostEditor, type PostEditorProps } from "@knit/react/ui";
import type { ReactNode } from "react";

// Add your own fields to the ready-made PostEditor: its children are drawn between the title and the body.
// Composer.Field calls the function only when the type has the field, so the label goes away with it.
function DevlogPostEditor(props: PostEditorProps) {
  return (
    <PostEditor {...props}>
      <Composer.Field<"devlog"> name="version">
        {({ value, setValue, disabled }) => (
          <label style={{ display: "block", marginBottom: 8 }}>
            Version
            <input
              value={typeof value === "string" ? value : ""}
              disabled={disabled}
              // Enter in an input would submit the editor, which publishes the post.
              onKeyDown={(e) => e.key === "Enter" && e.preventDefault()}
              onChange={(e) => setValue(e.target.value === "" ? undefined : e.target.value)}
            />
          </label>
        )}
      </Composer.Field>
    </PostEditor>
  );
}

// PostList and PostDetail use this editor for both new posts and edits.
const components = { PostEditor: DevlogPostEditor };

export function Providers({ children }: { children: ReactNode }) {
  return (
    <KnitProvider
      publishableKey={process.env.NEXT_PUBLIC_KNIT_PUBLISHABLE_KEY ?? ""}
      apiUrl={process.env.NEXT_PUBLIC_KNIT_API_URL ?? ""}
      components={components}
    >
      {children}
    </KnitProvider>
  );
}

children are drawn inside the <form>: give buttons type="button", and note that pressing Enter in an input submits the form as published. The ready-made comment form has no place to add fields.

With the hook, useKnitComposer holds typeKey and fields and sends them with the post. fields starts from the type's defaults for a new post and from the post's values when editing; setField(key, value) changes one (undefined clears it). When editing, only the fields you changed are sent, and a cleared field is sent as null; after a save, the values the server returned become the new starting point. Changing typeKey, space or the post being edited drops the values you typed. Keys the type doesn't have are never sent. Before sending, the composer checks the type's required fields (your own fields, the title, and the slug, tags and excerpt when an admin can fill them) and shows messages.errors.postRequiredFieldsMissing instead of sending. Reply drafts kept for signed-out readers include the fields.

devlog-hook.tsx
"use client";

import { useKnitComposer } from "@knit/react";

// With the .d.ts in your project, `fields` and `setField` follow the space's type: the root type
// ("devlog") here, because there's no parentId. setField("stage", "gamma") or setField("versoin", ...)
// is a type error.
export function VersionInput() {
  const composer = useKnitComposer({ space: "dev-log" });
  return (
    <input
      value={composer.fields.version ?? ""}
      onChange={(event) => composer.setField("version", event.target.value || undefined)}
    />
  );
}

// For a reply, the space's default reply type is used. Pass typeKey to use another reply type the
// space allows ("answer" here), and the fields follow that type.
export function AcceptedCheckbox({ rootId }: { rootId: string }) {
  const composer = useKnitComposer({ space: "dev-log", parentId: rootId, typeKey: "answer" });
  return (
    <input
      type="checkbox"
      checked={composer.fields.accepted ?? false}
      onChange={(event) => composer.setField("accepted", event.target.checked)}
    />
  );
}
  • Root posts use the space's root type. typeKey is optional for them.
  • Replies need space (the thread's space) as well. Without typeKey, replies use defaultReplyType; pass typeKey to use another of the space's reply types. A space that isn't the thread's space is refused with 400 SPACE_MISMATCH.
  • A post keeps its type. updatePost can't change it.

Reading fields

Every post carries typeKey and fields. A thread can mix reply types, so narrow a post with isKnitPostOfType(post, key) before reading a type's fields. Deleted posts and headline-only (locked) posts carry fields: {}, so isKnitPostOfType returns false for them. With the .d.ts, the narrowed fields has that type's shape.

devlog-card.tsx
import { type KnitPost, isKnitPostOfType } from "@knit/react";

// A thread can mix reply types. Narrow by typeKey to read each type's fields with their types.
export function ReplyBadge({ post }: { post: KnitPost }) {
  if (isKnitPostOfType(post, "answer") && post.fields.accepted) {
    return <span>Accepted answer</span>;
  }
  return null;
}

export function DevlogVersion({ post }: { post: KnitPost }) {
  if (!isKnitPostOfType(post, "devlog")) return null;
  return (
    <span>
      v{post.fields.version}
      {post.fields.stage ? ` (${post.fields.stage})` : null}
    </span>
  );
}

Locked posts (titles and excerpts only) always return fields: {}. Built-in fields a type sets to none come back empty (title: null, excerpt: null, tags: [], attachments: []).

Changing types

Posts are never rewritten when a type changes. Knit reads them with the current type:

  • Adding a required field needs a default. Posts without a value return the default, and are checked against the new rule the next time they are edited.
  • Removing a field hides its values; they stay stored, and adding the field back brings them back. The key is retired and can't be used for a different field. To erase the values for good (for example personal data), use Delete values in the console. That can't be undone.
  • Setting a built-in field to none works the same way: the stored values are kept and come back if you make it optional again.
  • A type that a space or a post uses can't be removed, and its kind (post or reply) can't change. The default types post and reply can't be removed, but you can change them.
  • If someone else applied a change while you were editing, applying answers 409 and the console offers to load the latest definition.

Errors

  • POST_TYPE_NOT_ALLOWED: The typeKey is not the space's root type, or not one of its reply types.
  • SPACE_MISMATCH: The space of a reply is not the space of the thread.
  • VALIDATION_ERROR: A field that the type doesn't have, a value of the wrong kind, or a missing required field. details.keys lists the fields.

See Error codes for how they are shown to readers.