DEV Community

AlixWang
AlixWang

Posted on

Building an AI Cron Builder with Cloudflare Pages and Next.js

Image description

This technical document outlines how to build an AI-powered cron expression builder using Cloudflare Pages, Next.js, and Cloudflare's AI capabilities. The result site is cronbuilder.online

Table of Contents

  1. Project Overview
  2. Technical Stack
  3. Setup and Configuration
  4. Key Components
  5. AI Integration
  6. Deployment

1. Project Overview

The AI Cron Builder is a web application that helps users create cron expressions through:

  • Natural language input processing using AI
  • Visual cron expression builder
  • Real-time validation

2. Technical Stack

  • Frontend Framework: Next.js 14
  • Hosting: Cloudflare Pages
  • AI Model: Cloudflare Workers AI (Llama 3)
  • UI Components: Ant Design
  • Styling: Tailwind CSS

3. Setup and Configuration

3.1 Project Structure

app/
├── api/
│   └── cron/         # AI endpoint
├── components/       # React components
├── layout.tsx       # Root layout
└── page.tsx         # Main page
Enter fullscreen mode Exit fullscreen mode

3.2 Edge Runtime Configuration

Enable edge runtime in your API routes by adding:

export const runtime = 'edge'
Enter fullscreen mode Exit fullscreen mode

3.3 Cloudflare Configuration

  1. Create a Cloudflare Pages project
  2. Enable Cloudflare AI in your project settings
  3. Configure environment variables for AI access

4. Key Components

4.1 Main Page Layout

The main page layout (referenced from app/page.tsx) includes:

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center px-12 bg-[#FAFDFF]">
      <header className="w-full h-16">
        <nav className="w-full h-full">
          <ul className="flex list-none h-full items-center justify-between">
            <li className="flex self-center items-center">
              <Image alt="logo" className="w-10 h-10 mr-2" width={100} height={100} src={"/logo.png"} />
              <h1 className="text-lg font-bold text-[#44779C]">Cron Builder</h1>
            </li>
            <li>
              <a role="button" tabIndex={0} href="mailto:service@cronbuilder.online" className="px-2.5 py-1 bg-blue-400 font-bold text-base text-white rounded-md">
                Contact
              </a>
            </li>
          </ul>
        </nav>
      </header>
      <h1 className="text-clip bg-clip-text text-transparent bg-[length:200%_100%] bg-ai animate-ai-animate-btn font-bold text-5xl text-center mt-10 ">
          Build Your Perfect
          <br/>
          Cron Expression Effortlessly
      </h1>
      <section className="w-full mt-8 flex justify-center">
        {/* <h2>Generate your cron expression</h2> */}
        <CronComp />
      </section>
      <section>

      </section>
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

4.2 Cron Component

The core cron builder component (referenced from app/components/cron/index.tsx) provides:

  • Visual cron expression builder
  • Expression validation
  • AI integration
const CronComp = () => {
    const [value, setValue] = useState('* * * * *');
    const [error, setError] = useState<boolean>(false);
    const handleCatchError = (error: CronError) => {
        if(error) {
            setError(true)
        } else {
            setError(false)
        }
    }

    return <ConfigProvider
        theme={
            {
                token: {
                    borderRadius: 0
                }
            }
        }
    >
        <div className='flex flex-col min-w-full'>
            <div>
                <AiGen onGenerate={(string) => {
                    if(string) {
                        setValue(string)
                    }
                }} />
            </div>
            <div>
                <Cron onError={handleCatchError} locale={NO_PREFIX_SUFFIX_LOCALE} value={value} setValue={setValue} />
            </div>
            <div>
                <Input status={error ? 'error' : ''} onChange={(e) => setValue(e.target.value)} value={value} />
            </div>
        </div>
    </ConfigProvider>
}
Enter fullscreen mode Exit fullscreen mode

4.3 AI Generation Component

The AI generation component (referenced from app/components/AiGen/index.tsx) handles:

  • User prompt input
  • AI request handling
  • Response processing
const AiGen:FC<AiGenProps> = ({onGenerate}) => {

    const [prompt, setPrompt] = useState<string>();
    const [loading, setLoading] = useState<boolean>(false);

    const btnClick = () => {
        if(loading) {
            return
        }
        setLoading(true);
        fetch('/api/cron', {
            method: 'POST',
            headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ prompt}),
        }).then(res => res.json()).then((res: any) => {
            onGenerate(res.response);
        }).finally(() => {
            setLoading(false);
        })
    }

    return <div className="flex flex-col">
        <Input.TextArea style={{resize: 'none'}} className='resize-none' placeholder="please input your prompt to generate the cron expression" onChange={(e) => setPrompt(e.target.value)} value={prompt} rows={4} />
        <button className={`${loading ? "cursor-wait" : ""} bg-[length:200%_100%] hover:animate-ai-animate-btn px-4 py-1 flex justify-center items-center mt-4 mb-4 self-end bg-ai text-white rounded-md`  }onClick={btnClick}>
            <span className='mr-2'>Run</span>
            <Image alt='image' width={10} height={10} src={"/magic.svg"} />
        </button>
    </div>
}
Enter fullscreen mode Exit fullscreen mode

5. AI Integration

5.1 API Route Setup

The cron API route (referenced from app/api/cron/route.ts) handles:

export async function POST(request: NextRequest) {
  // let responseText = 'Hello World'

  const { prompt } = await request.json<any>();
  const input = { prompt: `
      role: you are a cron expression master;
      capability: you can give valid cron expression by user nature language input;
      examples:
      Q: every minute invoke cron expression
      A: * * * * *

      Q: every hour at 30 minutes cron expression
      A: 30 * * * *

      Q: once a day cron expression
      A: 0 0 * * *

      Q: once a month
      A: 0 0 1 * *

      limit:
      1. no "?" or "#"  non-standard character.
      2. all cron expression only have 5 part(eg * * * * *).

      rule: 
      1. don't give me expression detail just give me result.
      2. the result must be a valid cron expression. 
      3. no extra useless string, just a cron expression (very important).

      now please generate cron by user input "${prompt}", if you can't give valid cron expression just told me "please try again"
    `};

  //@ts-ignore
  const answer = await getRequestContext().env.AI.run(
    "@cf/meta/llama-3-8b-instruct",
    input,
  );

  return new Response(JSON.stringify(answer))
}
Enter fullscreen mode Exit fullscreen mode

5.2 AI Prompt Template

The AI system uses a structured prompt template that includes:

  • Role definition
  • Capabilities
  • Examples
  • Rules and limitations

Example prompt structure:

const input = {
  prompt: `
    role: you are a cron expression master;
    capability: you can give valid cron expression by user nature language input;
    examples: [...]
    limit: [...]
    rule: [...]
  `
}
Enter fullscreen mode Exit fullscreen mode

5.3 Error Handling

Implement error handling for:

  • Invalid AI responses
  • Network failures
  • Invalid cron expressions

6. Deployment

6.1 Deployment Steps

  1. Push code to GitHub repository
  2. Connect repository to Cloudflare Pages
  3. Configure build settings:
   Build command: npm run build
   Build output directory: .next
Enter fullscreen mode Exit fullscreen mode

6.2 Environment Variables

Required environment variables:

  • AI: Cloudflare AI binding
  • NODE_VERSION: 18.x or higher

Best Practices

  1. Use edge runtime for optimal performance
  2. Implement proper error handling
  3. Add input validation
  4. Use TypeScript for type safety
  5. Follow responsive design principles
  6. Implement proper loading states

Limitations

  1. AI response time may vary
  2. Limited to standard cron expressions (5 parts)
  3. No support for special characters (?, #)
  4. Edge runtime restrictions

Conclusion

This project demonstrates how to build a modern AI-powered web application using Cloudflare's ecosystem and Next.js. The combination provides a scalable, performant solution for generating cron expressions through both visual interface and AI assistance.

For more information, refer to:

Top comments (1)

Collapse
 
waynetyler profile image
WayneTyler

This is a cool project! I love how Cloudflare Pages and Next.js come together to make something like this so powerful. If you’re looking for more hosting options, Cloudways could be a great fit for those looking to run similar Next.js applications on a managed platform with flexibility. DigitalOcean or Vercel are also solid options for quick deployments.