npm package: @rehantz/cms-renderer
Description: Universal React Blog Renderer - Display blogs from Global CMS in any React/Next.js/Laravel application
Author: Techozon
Latest version: 1.0.8

# CMS Renderer

[![npm version](https://badge.fury.io/js/@rehantz%2Fcms-renderer.svg)](https://www.npmjs.com/package/@rehantz/cms-renderer)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A **Universal React Blog Renderer** that displays blogs from [Global CMS](https://blogcms.techozon.com) in any React, Next.js, or Laravel application. Just add your Organization ID and you're ready to go!

## ✨ Features

- 🎨 **4 Beautiful Themes**: Grid, Minimal, Magazine, Masonry
- 🌓 **Light & Dark Mode**: Auto (system), Light, or Dark
- 📱 **Fully Responsive**: Mobile-first design
- 🔍 **Built-in Search**: Filter posts instantly
- 📄 **Pagination**: Smart pagination with smooth navigation
- ⚡ **Fast**: Optimized for performance
- 🎯 **Zero Config**: Just add your Organization ID
- 🛡️ **Scoped Styles**: CSS won't conflict with your app
- 🚀 **CLI Init Tool**: Set up in seconds

---

## 📋 Table of Contents

- [Quick Start (Recommended)](#-quick-start-recommended)
- [Prerequisites](#-prerequisites)
- [Get Your Organization ID](#-get-your-organization-id)
- [Next.js Manual Installation](#-nextjs-manual-installation)
- [Laravel Installation](#-laravel-installation)
- [Configuration Options](#️-configuration-options)
- [Themes](#-themes)
- [Color Modes](#-color-modes)
- [Customization](#-customization)
- [Troubleshooting](#-troubleshooting)

---

## 🚀 Quick Start (Recommended)

The fastest way to get started is using our CLI tool. It automatically detects your project type (Next.js or React) and creates all the necessary files.

### Step 1: Install the Package

```bash
npm install @rehantz/cms-renderer
```

### Step 2: Run the Init Command

```bash
npx @rehantz/create-cms-blog
```

### Step 3: Follow the Prompts

```
🚀 CMS Renderer Setup
Set up a blog in your project in seconds!

✔ Detected project type: Next.js

? Enter your Organization ID from Global CMS: › your-org-id-here
? Choose a theme: › Grid - Modern card layout
? Choose color mode: › Auto - Follow system preference

📁 Creating files...

✔ Created app/blog/page.tsx
✔ Created app/blog/[...slug]/page.tsx
✔ Created .env.local

✅ Setup complete!

Next steps:
  1. Start your development server:
     npm run dev

  2. Visit your blog at:
     http://localhost:3000/blog
```

That's it! Your blog is ready! 🎉

---

## 📋 Prerequisites

Before you begin, ensure you have:

- **Node.js** 18.0 or higher
- **npm**, **yarn**, or **pnpm**
- An account at [Global CMS](https://blogcms.techozon.com)

---

## 🔑 Get Your Organization ID

1. Go to [Global CMS](https://blogcms.techozon.com)
2. Sign up or log in
3. Navigate to **Integration** in the sidebar
4. Copy your **Organization ID**

---

## ⚡ Next.js Manual Installation

If you prefer manual setup, follow these steps:

### Step 1: Install the Package

```bash
npm install @rehantz/cms-renderer
# or
yarn add @rehantz/cms-renderer
# or
pnpm add @rehantz/cms-renderer
```

### Step 2: Create Environment File

Create `.env.local` in your project root:

```env
# CMS Renderer Configuration
NEXT_PUBLIC_CMS_ORGANIZATION_ID=your-organization-id-here
NEXT_PUBLIC_CMS_API_URL=https://blogcms.techozon.com/api
```

### Step 3: Import CSS in Layout

Add the CSS import to your root layout file:

```tsx
// app/layout.tsx
import type { Metadata } from "next";
import "./globals.css";
import "@rehantz/cms-renderer/styles.css"; // Add this line

export const metadata: Metadata = {
  title: "My Blog",
  description: "Powered by CMS Renderer",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}
```

### Step 4: Create Blog Page

Create your blog page:

```tsx
// app/blog/page.tsx
'use client';

import { BlogRenderer } from '@rehantz/cms-renderer';

export default function BlogPage() {
  return (
    <BlogRenderer
      organizationId={process.env.NEXT_PUBLIC_CMS_ORGANIZATION_ID!}
      apiUrl={process.env.NEXT_PUBLIC_CMS_API_URL || 'https://blogcms.techozon.com/api'}
      theme="grid"
      colorMode="dark"
      basePath="/blog"
      showHeader={true}
      showSearch={true}
      postsPerPage={9}
    />
  );
}
```

### Step 5: Create Catch-All Route for Blog Posts

Create a catch-all route to handle individual blog post URLs:

```tsx
// app/blog/[...slug]/page.tsx
'use client';

import { BlogRenderer } from '@rehantz/cms-renderer';

export default function BlogPostPage() {
  return (
    <BlogRenderer
      organizationId={process.env.NEXT_PUBLIC_CMS_ORGANIZATION_ID!}
      apiUrl={process.env.NEXT_PUBLIC_CMS_API_URL || 'https://blogcms.techozon.com/api'}
      theme="grid"
      colorMode="dark"
      basePath="/blog"
      showHeader={true}
      showSearch={true}
      postsPerPage={9}
    />
  );
}
```

### Step 6: Run Your App

```bash
npm run dev
```

Visit `http://localhost:3000/blog` to see your blog!

---

## 🐘 Laravel Installation

### Step 1: Create Laravel Project (Skip if existing)

```bash
composer create-project laravel/laravel my-blog
cd my-blog
```

### Step 2: Install NPM Dependencies

```bash
npm install
npm install react react-dom @vitejs/plugin-react @rehantz/cms-renderer
```

### Step 3: Configure Vite for React

Update `vite.config.js`:

```javascript
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.jsx'],
            refresh: true,
        }),
        react(),
    ],
});
```

### Step 4: Create React Entry Point

Create `resources/js/app.jsx`:

```jsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import { BlogRenderer } from '@rehantz/cms-renderer';
import '@rehantz/cms-renderer/styles.css';

// Get configuration from window (set by Laravel blade)
const config = window.CMS_CONFIG || {};

const container = document.getElementById('cms-blog');

if (container) {
    const root = createRoot(container);
    root.render(
        <BlogRenderer
            organizationId={config.organizationId || ''}
            apiUrl={config.apiUrl || 'https://blogcms.techozon.com/api'}
            theme={config.theme || 'grid'}
            colorMode={config.colorMode || 'dark'}
            basePath={config.basePath || '/blog'}
            showHeader={config.showHeader !== false}
            showSearch={config.showSearch !== false}
            postsPerPage={config.postsPerPage || 9}
        />
    );
}
```

### Step 5: Create CMS Config File

Create `config/cms.php`:

```php
<?php

return [
    // Your Organization ID from Global CMS dashboard
    'organization_id' => env('CMS_ORGANIZATION_ID', ''),

    // API URL (default: Global CMS API)
    'api_url' => env('CMS_API_URL', 'https://blogcms.techozon.com/api'),

    // Theme: grid, minimal, magazine, masonry
    'theme' => env('CMS_THEME', 'grid'),

    // Color Mode: auto, light, dark
    'color_mode' => env('CMS_COLOR_MODE', 'dark'),
];
```

### Step 6: Create Blade Template

Create `resources/views/blog/index.blade.php`:

```blade
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ config('app.name') }} - Blog</title>
    @vite(['resources/css/app.css', 'resources/js/app.jsx'])
</head>
<body>
    <!-- CMS Blog Container -->
    <div id="cms-blog"></div>

    <!-- Pass configuration to JavaScript -->
    <script>
        window.CMS_CONFIG = {
            organizationId: "{{ config('cms.organization_id') }}",
            apiUrl: "{{ config('cms.api_url') }}",
            theme: "{{ config('cms.theme', 'grid') }}",
            colorMode: "{{ config('cms.color_mode', 'dark') }}",
            basePath: "/blog",
            showHeader: true,
            showSearch: true,
            postsPerPage: 9
        };
    </script>
</body>
</html>
```

### Step 7: Add Routes

Update `routes/web.php`:

```php
<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

// Blog routes
Route::get('/blog', function () {
    return view('blog.index');
});

// Catch-all for blog post slugs (client-side routing)
Route::get('/blog/{slug}', function () {
    return view('blog.index');
})->where('slug', '.*');
```

### Step 8: Configure Environment

Add to your `.env` file:

```env
# CMS Renderer Configuration
CMS_ORGANIZATION_ID=your-organization-id-here
CMS_API_URL=https://blogcms.techozon.com/api
CMS_THEME=grid
CMS_COLOR_MODE=dark

# IMPORTANT: Use file sessions to avoid database issues
SESSION_DRIVER=file
```

> ⚠️ **Important**: Change `SESSION_DRIVER=database` to `SESSION_DRIVER=file` to avoid SQLite driver errors.

### Step 9: Build and Run

```bash
# Build assets
npm run build

# Start Laravel server
php artisan serve
```

Visit `http://localhost:8000/blog` to see your blog!

---

## ⚙️ Configuration Options

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `organizationId` | `string` | **required** | Your Organization ID from CMS |
| `apiUrl` | `string` | **required** | CMS API URL |
| `theme` | `string` | `'grid'` | Layout theme |
| `colorMode` | `string` | `'auto'` | Color mode |
| `basePath` | `string` | `'/blog'` | Base URL path for routing |
| `showHeader` | `boolean` | `true` | Show organization header |
| `showSearch` | `boolean` | `true` | Show search input |
| `postsPerPage` | `number` | `9` | Posts per page |
| `locale` | `string` | `'en-US'` | Date formatting locale |

---

## 🎨 Themes

| Theme | Description | Best For |
|-------|-------------|----------|
| `grid` | Modern card grid layout | Tech blogs, Portfolios |
| `minimal` | Clean list style layout | Writers, Journals |
| `magazine` | Featured hero with sidebar | News, Media |
| `masonry` | Pinterest-style columns | Visual content |

### Theme Examples

```tsx
// Grid Theme (Default) - Modern card layout
<BlogRenderer theme="grid" ... />

// Minimal Theme - Clean list style
<BlogRenderer theme="minimal" ... />

// Magazine Theme - Featured hero layout
<BlogRenderer theme="magazine" ... />

// Masonry Theme - Pinterest-style columns
<BlogRenderer theme="masonry" ... />
```

---

## 🌓 Color Modes

| Mode | Description |
|------|-------------|
| `auto` | Follows system preference (default) |
| `light` | Always light mode |
| `dark` | Always dark mode |

### Color Mode Examples

```tsx
// Auto (follows system preference)
<BlogRenderer colorMode="auto" ... />

// Force Light Mode
<BlogRenderer colorMode="light" ... />

// Force Dark Mode
<BlogRenderer colorMode="dark" ... />
```

---

## 🔧 Customization

### Override CSS Variables

Add custom styles to override the default design:

```css
/* In your global CSS */
.cms-renderer {
  --cms-accent-color: #your-brand-color;
  --cms-font-sans: 'Your Font', sans-serif;
  --cms-radius-lg: 1rem;
}
```

### Available CSS Variables

```css
/* Colors */
--cms-bg-primary          /* Primary background */
--cms-bg-secondary        /* Secondary background */
--cms-text-primary        /* Primary text color */
--cms-text-secondary      /* Secondary text color */
--cms-accent-color        /* Accent/brand color */
--cms-border-color        /* Border color */

/* Typography */
--cms-font-sans           /* Sans-serif font */
--cms-font-serif          /* Serif font */

/* Spacing */
--cms-space-sm            /* Small spacing */
--cms-space-md            /* Medium spacing */
--cms-space-lg            /* Large spacing */

/* Border Radius */
--cms-radius-sm           /* Small radius */
--cms-radius-md           /* Medium radius */
--cms-radius-lg           /* Large radius */
```

---

## 🐛 Troubleshooting

### Common Issues and Solutions

#### ❌ "No posts found"

**Cause**: Your blogs are in Draft status or Organization ID is incorrect.

**Solution**:
1. Log in to [Global CMS](https://blogcms.techozon.com)
2. Make sure your blogs are **Published** (not Draft)
3. Verify your Organization ID is correct

---

#### ❌ Styles not loading (Next.js)

**Cause**: CSS import is missing.

**Solution**: Add the CSS import in your layout file:
```tsx
// app/layout.tsx
import '@rehantz/cms-renderer/styles.css';
```

---

#### ❌ SQLite driver error (Laravel)

```
could not find driver (Connection: sqlite)
```

**Cause**: Laravel is trying to use SQLite for sessions but the driver isn't installed.

**Solution**: Change session driver to file in `.env`:
```env
SESSION_DRIVER=file
```

---

#### ❌ "Cannot read properties of undefined (reading 'avatar')"

**Cause**: Old version of the library.

**Solution**: Update to the latest version:
```bash
npm update @rehantz/cms-renderer
```

---

#### ❌ CORS errors

**Cause**: Network or proxy issues.

**Solution**: 
- The CMS API allows all origins by default
- Check your network/proxy configuration
- Verify the API URL is correct

---

#### ❌ Module not found errors

**Cause**: Missing dependencies.

**Solution**: Install all required dependencies:
```bash
# For Next.js
npm install @rehantz/cms-renderer

# For Laravel
npm install react react-dom @vitejs/plugin-react @rehantz/cms-renderer
```

---

## 🔒 Security

- ✅ Uses **public, read-only** API endpoints only
- ✅ No API keys exposed to the client
- ✅ Only **published** blog posts are visible
- ✅ CORS properly configured
- ✅ No sensitive data transmitted

---

## 📝 Publishing Your Blogs

1. Log in to [Global CMS](https://blogcms.techozon.com)
2. Create or edit a blog post
3. Change status from **Draft** to **Published**
4. Save the post
5. The post will appear in your app automatically

---

## 📦 Version History

| Version | Changes |
|---------|---------|
| 1.0.2 | Fixed undefined author error, improved error handling |
| 1.0.1 | Added Laravel documentation, improved README |
| 1.0.0 | Initial release |

---

## 📄 License

MIT © [Techozon](https://techozon.com)

---

## 🔗 Links

- [Global CMS Dashboard](https://blogcms.techozon.com)
- [NPM Package](https://www.npmjs.com/package/@rehantz/cms-renderer)
- [CLI Tool](https://www.npmjs.com/package/@rehantz/create-cms-blog)
- [GitHub Repository](https://github.com/techozon/cms-renderer)
- [Report Issues](https://github.com/techozon/cms-renderer/issues)

---

## 💬 Support

Need help? Have questions?

- 📧 Email: support@techozon.com
- 🐛 [Report a Bug](https://github.com/techozon/cms-renderer/issues)
- 💡 [Request a Feature](https://github.com/techozon/cms-renderer/issues)