---
title: Schedule Slack posts with Next.js, Workflow, and Neon
description: This guide walks through scheduling Slack channel posts with Chat SDK, persisting schedules in Neon, and using Workflow sleep timers for durable delivery.
type: guide
prerequisites: []
related:
  - /docs/guides/slack-nextjs
  - /docs/slash-commands
  - /docs/state/postgres
  - /docs/api/channel
  - /docs/api/chat
---

Chat SDK already supports native scheduled messages on Slack with `thread.schedule()` and `channel.schedule()`. That is useful for simple Slack-only cases.

This guide uses a different pattern: Workflow owns the timer with `sleep()`, and Neon stores the schedule as your source of truth. That gives you a more durable scheduling system you can extend with cancellation, rescheduling, approvals, and cross-platform delivery later.

The example uses Slack slash commands to schedule top-level channel posts.

## Prerequisites

- Node.js 18+
- [pnpm](https://pnpm.io) (or npm/yarn)
- A Next.js App Router project
- A Slack workspace where you can install apps
- A Neon Postgres database

<Callout type="info">
  If you still need Slack app setup and the webhook route, start with [Slack bot with Next.js and Redis](/docs/guides/slack-nextjs), then come back here and swap the state adapter to PostgreSQL.
</Callout>

## Install the dependencies

Install Chat SDK, the Slack adapter, the PostgreSQL state adapter, Workflow, and `pg`:

```sh title="Terminal"
pnpm add chat @chat-adapter/slack @chat-adapter/state-pg workflow pg
```

## Create a Neon database

Create a Neon project, copy its **pooled** Postgres connection string, and store it as `POSTGRES_URL`.

`createPostgresState()` already supports `POSTGRES_URL` and `DATABASE_URL`, so the same Neon database can back both Chat SDK state and your app's schedule table.

## Configure environment variables

Create a `.env.local` file:

```bash title=".env.local"
SLACK_BOT_TOKEN=xoxb-your-bot-token
SLACK_SIGNING_SECRET=your-signing-secret
POSTGRES_URL=postgresql://user:password@your-neon-host-pooler.neon.tech/neondb?sslmode=require
```

## Enable Workflow in Next.js

Wrap your Next.js config with `withWorkflow()` so `"use workflow"` and `"use step"` directives are compiled:

```typescript title="next.config.ts" lineNumbers
import { withWorkflow } from "workflow/next";
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  // ...your existing config
};

export default withWorkflow(nextConfig);
```

<Callout type="info">
  If your app uses `proxy.ts`, exclude `.well-known/workflow/` from the matcher so Workflow's internal routes are not intercepted.
</Callout>

## Add slash commands to Slack

Add two slash commands to your Slack app and point both at your webhook route:

```yaml title="slack-manifest.yml"
features:
  slash_commands:
    - command: /remind
      url: https://your-domain.com/api/webhooks/slack
      description: Schedule a channel post
      usage_hint: "<ISO-8601 timestamp> <message>"
      should_escape: false
    - command: /remind-cancel
      url: https://your-domain.com/api/webhooks/slack
      description: Cancel a scheduled post
      usage_hint: "<schedule-id>"
      should_escape: false
```

If you're starting from scratch rather than the Slack guide, make sure your app also has the `commands` and `chat:write` bot scopes in **OAuth & Permissions**, then reinstall the app after changing scopes.

This guide keeps parsing simple by accepting an ISO timestamp like `2026-03-15T09:00:00Z`.

## Create the schedule table in Neon

Run this SQL in the Neon SQL Editor:

```sql title="schema.sql"
CREATE TABLE scheduled_posts (
  id text PRIMARY KEY,
  channel_id text NOT NULL,
  message text NOT NULL,
  post_at timestamptz NOT NULL,
  status text NOT NULL CHECK (status IN ('pending', 'sent', 'canceled')),
  workflow_run_id text,
  created_by text NOT NULL,
  sent_at timestamptz,
  canceled_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX scheduled_posts_status_post_at_idx
  ON scheduled_posts (status, post_at);
```

## Create the Postgres client

Use a shared `pg` pool for your own schedule records:

```typescript title="lib/db.ts" lineNumbers
import pg from "pg";

if (!process.env.POSTGRES_URL) {
  throw new Error("POSTGRES_URL is required");
}

export const pool = new pg.Pool({
  connectionString: process.env.POSTGRES_URL,
});
```

## Create the Chat instance

Use Neon for Chat SDK state by switching to the PostgreSQL state adapter:

```typescript title="lib/bot.ts" lineNumbers
import { createSlackAdapter } from "@chat-adapter/slack";
import { createPostgresState } from "@chat-adapter/state-pg";
import { Chat } from "chat";

export const bot = new Chat({
  userName: "reminder-bot",
  adapters: {
    slack: createSlackAdapter(),
  },
  state: createPostgresState(),
});
```

## Add schedule helpers

Create a small data layer for inserting, loading, updating, and canceling scheduled posts:

```typescript title="lib/scheduled-posts.ts" lineNumbers
import { randomUUID } from "node:crypto";
import { pool } from "@/lib/db";

export interface ScheduledPost {
  id: string;
  channelId: string;
  message: string;
  postAt: string;
  status: "pending" | "sent" | "canceled";
  workflowRunId: string | null;
}

export async function createScheduledPost(input: {
  channelId: string;
  createdBy: string;
  message: string;
  postAt: Date;
}) {
  const id = randomUUID();

  await pool.query(
    `INSERT INTO scheduled_posts (
      id, channel_id, message, post_at, status, created_by
    ) VALUES ($1, $2, $3, $4, 'pending', $5)`,
    [id, input.channelId, input.message, input.postAt, input.createdBy]
  );

  return { id, ...input, postAt: input.postAt.toISOString() };
}

export async function getScheduledPost(id: string): Promise<ScheduledPost | null> {
  const result = await pool.query(
    `SELECT id, channel_id, message, post_at, status, workflow_run_id
     FROM scheduled_posts
     WHERE id = $1
     LIMIT 1`,
    [id]
  );

  if (result.rows.length === 0) {
    return null;
  }

  const row = result.rows[0];
  return {
    id: row.id as string,
    channelId: row.channel_id as string,
    message: row.message as string,
    postAt: (row.post_at as Date).toISOString(),
    status: row.status as ScheduledPost["status"],
    workflowRunId: (row.workflow_run_id as string | null) ?? null,
  };
}

export async function attachWorkflowRun(id: string, runId: string) {
  await pool.query(
    `UPDATE scheduled_posts
     SET workflow_run_id = $2
     WHERE id = $1`,
    [id, runId]
  );
}

export async function markScheduledPostSent(id: string) {
  await pool.query(
    `UPDATE scheduled_posts
     SET status = 'sent', sent_at = now()
     WHERE id = $1 AND status = 'pending'`,
    [id]
  );
}

export async function cancelScheduledPost(id: string, createdBy: string) {
  const result = await pool.query(
    `UPDATE scheduled_posts
     SET status = 'canceled', canceled_at = now()
     WHERE id = $1 AND created_by = $2 AND status = 'pending'`,
    [id, createdBy]
  );

  return (result.rowCount ?? 0) > 0;
}
```

## Create the workflow

The workflow only orchestrates. All Postgres access and Slack posting stay in `"use step"` functions:

```typescript title="workflows/send-scheduled-post.ts" lineNumbers
import { sleep } from "workflow";
import { bot } from "@/lib/bot";
import {
  getScheduledPost,
  markScheduledPostSent,
} from "@/lib/scheduled-posts";

async function loadScheduledPost(scheduleId: string) {
  "use step";
  return getScheduledPost(scheduleId);
}

async function postToChannel(channelId: string, message: string) {
  "use step";

  await bot.initialize();

  const channel = bot.channel(channelId);
  await channel.post(message);
}

async function completeScheduledPost(scheduleId: string) {
  "use step";
  await markScheduledPostSent(scheduleId);
}

export async function sendScheduledPost(scheduleId: string) {
  "use workflow";

  const schedule = await loadScheduledPost(scheduleId);
  if (!schedule || schedule.status !== "pending") {
    return;
  }

  await sleep(new Date(schedule.postAt));

  // Re-check the row after waking up in case it was canceled.
  const fresh = await loadScheduledPost(scheduleId);
  if (!fresh || fresh.status !== "pending") {
    return;
  }

  await postToChannel(fresh.channelId, fresh.message);
  await completeScheduledPost(scheduleId);
}
```

This is the key Workflow pattern:

- schedule creation writes a row in Neon first
- the workflow sleeps until `postAt`
- the workflow reloads the row after waking up
- canceled schedules no-op instead of posting

That makes cancellation simple and durable.

## Register the slash command handlers

Create a side-effect module that parses commands, writes rows to Neon, starts workflows, and handles cancellation:

```typescript title="lib/reminder-handlers.ts" lineNumbers
import { start } from "workflow/api";
import { bot } from "@/lib/bot";
import {
  attachWorkflowRun,
  cancelScheduledPost,
  createScheduledPost,
} from "@/lib/scheduled-posts";
import { sendScheduledPost } from "@/workflows/send-scheduled-post";

function parseReminderInput(input: string) {
  const trimmed = input.trim();
  const firstSpace = trimmed.indexOf(" ");

  if (firstSpace === -1) {
    return null;
  }

  const timestamp = trimmed.slice(0, firstSpace);
  const message = trimmed.slice(firstSpace + 1).trim();
  const postAt = new Date(timestamp);

  if (!message || Number.isNaN(postAt.getTime()) || postAt <= new Date()) {
    return null;
  }

  return { message, postAt };
}

bot.onSlashCommand("/remind", async (event) => {
  const parsed = parseReminderInput(event.text);

  if (!parsed) {
    await event.channel.postEphemeral(
      event.user,
      "Usage: `/remind 2026-03-15T09:00:00Z Review launch checklist`",
      { fallbackToDM: false }
    );
    return;
  }

  const scheduled = await createScheduledPost({
    channelId: event.channel.id,
    createdBy: event.user.userId,
    message: parsed.message,
    postAt: parsed.postAt,
  });

  const run = await start(sendScheduledPost, [scheduled.id]);
  await attachWorkflowRun(scheduled.id, run.runId);

  await event.channel.postEphemeral(
    event.user,
    `Scheduled \`${scheduled.id}\` for ${parsed.postAt.toISOString()}.`,
    { fallbackToDM: false }
  );
});

bot.onSlashCommand("/remind-cancel", async (event) => {
  const scheduleId = event.text.trim();

  if (!scheduleId) {
    await event.channel.postEphemeral(
      event.user,
      "Usage: `/remind-cancel <schedule-id>`",
      { fallbackToDM: false }
    );
    return;
  }

  const canceled = await cancelScheduledPost(scheduleId, event.user.userId);

  await event.channel.postEphemeral(
    event.user,
    canceled
      ? `Canceled \`${scheduleId}\`.`
      : `No pending schedule found for \`${scheduleId}\`.`,
    { fallbackToDM: false }
  );
});
```

The cancellation path is intentionally simple. It only updates the database row, and it only allows the creator of the schedule to cancel it. If the workflow wakes up later, it re-checks the row and exits without posting.

If you want workspace admins or moderators to cancel other users' schedules, extend the cancellation query with your own permission rules instead of removing the ownership check.

## Create the webhook route

Import the handler module once so the slash command handlers are registered:

```typescript title="app/api/webhooks/[platform]/route.ts" lineNumbers
import "@/lib/reminder-handlers";
import { after } from "next/server";
import { bot } from "@/lib/bot";

type Platform = keyof typeof bot.webhooks;

export async function POST(
  request: Request,
  context: RouteContext<"/api/webhooks/[platform]">
) {
  const { platform } = await context.params;

  const handler = bot.webhooks[platform as Platform];
  if (!handler) {
    return new Response(`Unknown platform: ${platform}`, { status: 404 });
  }

  return handler(request, {
    waitUntil: (task) => after(() => task),
  });
}
```

## Test locally

1. Start your development server with `pnpm dev`
2. Expose it with a tunnel such as `ngrok http 3000`
3. Update your Slack slash command URLs to the tunnel URL
4. In Slack, run `/remind 2026-03-15T09:00:00Z Review launch checklist`
5. Confirm that you receive an ephemeral confirmation with a schedule ID
6. Wait for the scheduled time and verify the bot posts to the channel
7. Create another one and cancel it with `/remind-cancel <schedule-id>`

## Extending the pattern

From here you can add:

- rescheduling by canceling the old row and creating a new one
- recurring posts by having the workflow create the next schedule before it exits
- approvals by pausing the workflow with a hook before posting
- thread reminders by storing `thread.toJSON()` instead of `channelId` and restoring it with `bot.reviver()`

## Next steps

- [Slack bot with Next.js and Redis](/docs/guides/slack-nextjs) — Base Slack app and webhook setup
- [Slash Commands](/docs/slash-commands) — Command handling patterns
- [PostgreSQL State Adapter](/docs/state/postgres) — Using Postgres for Chat SDK state
- [Channel API](/docs/api/channel) — Posting to channels and working with channel IDs
- [Chat API](/docs/api/chat) — `bot.channel()` and lifecycle management
