UNPKG

fireship-ai-blog

Version:

A beautiful, SEO-friendly blog package for Next.js 13+ with Fireship.ai API integration

539 lines (414 loc) 11.2 kB
# @fireship-ai/blog A beautiful, SEO-friendly blog package for Next.js 13+ with Fireship.ai API integration. Features modern UI design, interactive components, and seamless integration. ## Features - 🎨 **Modern UI**: Clean design with NextUI and TailwindCSS - 📝 **Blog Components**: Ready-to-use blog post viewer and navigation - 🎯 **SEO Optimized**: Automatic meta tags and Open Graph support - 🌙 **Dark Mode**: Full dark/light mode support with zinc color palette - 📱 **Responsive**: Mobile-first design that works on all devices - ⚡ **Server Components**: Next.js 13+ App Router with SSR support - 🔗 **Interactive**: Like, save, and share functionality built-in - 🎨 **Customizable**: Sidebar layouts and content organization ## Installation ```bash npm install fireship-ai-blog # or yarn add fireship-ai-blog # or bun add fireship-ai-blog ``` ## Quick Start ### 1. Add Environment Variable ```bash # .env.local NEXT_PUBLIC_FIRESHIP_BLOG_PUBLISHABLE_KEY=your_api_key_here ``` ### 2. Create API Route ```tsx // app/api/fireship-blog/[...path]/route.ts import { createFireshipProxyHandler } from 'fireship-ai-blog'; const base = createFireshipProxyHandler({ apiBase: 'https://fireship.ai/api/blog', getApiKey: () => process.env.FIRESHIP_BLOG_API_KEY || process.env.NEXT_PUBLIC_FIRESHIP_BLOG_PUBLISHABLE_KEY, allowOrigin: 'http://localhost:3000', domain: 'your-domain.com' // Your website domain }); export async function GET(req: Request, ctx: { params: Promise<{ path?: string[] }> }) { const resolved = ctx?.params ? await ctx.params : undefined; return base.GET(req, { params: resolved }); } export function OPTIONS() { return base.OPTIONS(); } ``` ### 3. Use the Component ```tsx // app/blog/page.tsx import { FireshipBlog } from 'fireship-ai-blog' export default function BlogPage() { return <FireshipBlog /> } ``` That's it! The component handles: - ✅ Blog post listing - ✅ Individual post viewing (with URL slugs) - ✅ Navigation between posts - ✅ All API calls internally - ✅ Loading states and error handling ### Dependencies The package automatically includes all core dependencies: - **TipTap** (rich text editor) - **React Markdown** (markdown rendering) - **Recharts** (analytics charts) - **Utility libraries** (clsx, tailwind-merge) You only need these **peer dependencies** (likely already in your project): - React 18+ - Next.js 13+ - Tailwind CSS 3+ - Lucide React (for icons) Install peer dependencies if missing: ```bash npm install react react-dom next tailwindcss lucide-react ``` ## Setup ### 1. Environment Variables Add your Fireship.ai API key to your `.env.local` file: ```env NEXT_PUBLIC_FIRESHIP_BLOG_PUBLISHABLE_KEY=your_api_key_here ``` ### 2. Import Styles Add the CSS import to your `globals.css` file: ```css @import 'fireship-blog/styles/blog.css'; ``` ### 3. Tailwind Configuration Add the package to your `tailwind.config.js`: ```js module.exports = { content: [ // ... your existing content paths './node_modules/fireship-blog/**/*.{js,ts,jsx,tsx}', ], // ... rest of your config } ``` ## Usage ### Basic Blog Page Create a blog page at `app/blog/page.tsx`: ```tsx import { FireshipBlog } from 'fireship-blog'; export default function BlogPage() { return <FireshipBlog />; } ``` ### Single Post Page Create a dynamic post page at `app/blog/[slug]/page.tsx`: ```tsx import { FireshipBlog } from 'fireship-blog'; interface BlogPostPageProps { params: { slug: string }; } export default function BlogPostPage({ params }: BlogPostPageProps) { return <FireshipBlog slug={params.slug} />; } ``` ### Admin Dashboard Create an admin page at `app/blog/admin/page.tsx`: ```tsx import { FireshipBlogAdmin } from 'fireship-blog'; export default function BlogAdminPage() { return <FireshipBlogAdmin />; } ``` ### Category/Tag Pages ```tsx import { FireshipBlog } from 'fireship-blog'; export default function CategoryPage({ params }: { params: { category: string } }) { return <FireshipBlog category={params.category} />; } ``` ## Components ### FireshipBlog The main blog component for displaying posts and single post views. ```tsx <FireshipBlog domain="your-domain.com" // Required: Your website domain slug="optional-post-slug" category="optional-category" tag="optional-tag" limit={10} showRelatedPosts={true} showNavigation={true} customTheme={{ primaryColor: '#3b82f6', glassEffect: true, }} /> ``` ### FireshipBlogAdmin Admin dashboard for managing posts, analytics, and theme settings. ```tsx <FireshipBlogAdmin onSave={(post) => console.log('Post saved:', post)} onDelete={(postId) => console.log('Post deleted:', postId)} /> ``` ### PostEditor Rich text editor component with markdown support. ```tsx <PostEditor post={existingPost} onSave={async (postData) => { // Handle save }} onCancel={() => { // Handle cancel }} /> ``` ### PostCard Individual post card component. ```tsx <PostCard post={blogPost} onClick={(post) => router.push(`/blog/${post.slug}`)} showAnalytics={true} /> ``` ### AnalyticsDashboard Analytics dashboard with charts and metrics. ```tsx <AnalyticsDashboard postId="optional-specific-post" dateRange={{ from: '2024-01-01', to: '2024-12-31' }} /> ``` ### ThemeSettings Theme customization component. ```tsx <ThemeSettings settings={currentTheme} onSave={async (newTheme) => { // Save theme settings }} /> ``` ## Hooks ### useFireshipPosts Hook for fetching and managing blog posts. ```tsx import { useFireshipPosts } from 'fireship-blog'; function BlogComponent() { const { posts, loading, error, hasMore, loadMore, refresh, totalCount } = useFireshipPosts({ category: 'tech', limit: 10, status: 'published' }); if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; return ( <div> {posts.map(post => ( <PostCard key={post.id} post={post} /> ))} {hasMore && ( <button onClick={loadMore}>Load More</button> )} </div> ); } ``` ### useFireshipPost Hook for fetching a single post. ```tsx import { useFireshipPost } from 'fireship-blog'; function SinglePostComponent({ slug }: { slug: string }) { const { post, loading, error } = useFireshipPost(slug); if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; if (!post) return <div>Post not found</div>; return ( <article> <h1>{post.title}</h1> <div dangerouslySetInnerHTML={{ __html: post.content }} /> </article> ); } ``` ### useFireshipTheme Hook for managing theme settings. ```tsx import { useFireshipTheme } from 'fireship-blog'; function ThemeToggle() { const { theme, updateTheme } = useFireshipTheme(); const toggleGlassEffect = () => { updateTheme({ ...theme, glassEffect: !theme.glassEffect }); }; return ( <button onClick={toggleGlassEffect}> {theme.glassEffect ? 'Disable' : 'Enable'} Glass Effect </button> ); } ``` ## API Reference ### Core API Functions ```tsx import { getPosts, getPostBySlug, getRelatedPosts, submitPost, getAnalytics, updateThemeSettings } from 'fireship-blog'; // Fetch posts const posts = await getPosts({ page: 1, limit: 10, category: 'tech', status: 'published' }); // Get single post const post = await getPostBySlug('my-blog-post'); // Submit new/updated post const savedPost = await submitPost({ title: 'My New Post', content: '# Hello World\n\nThis is my post content.', status: 'published' }); // Get analytics const analytics = await getAnalytics({ postId: 'optional-post-id', dateFrom: '2024-01-01', dateTo: '2024-12-31' }); ``` ### Markdown Utilities ```tsx import { markdownToHtml, htmlToMarkdown, calculateReadingTime, extractExcerpt, validateMarkdown } from 'fireship-blog'; // Convert markdown to HTML const html = await markdownToHtml('# Hello World'); // Calculate reading time const readingTime = calculateReadingTime(markdownContent); // Extract excerpt const excerpt = extractExcerpt(markdownContent, 160); // Validate markdown const { isValid, errors, warnings } = validateMarkdown(content); ``` ## Theme Customization ### Default Theme ```tsx import { defaultTheme } from 'fireship-blog'; const customTheme = { ...defaultTheme, primaryColor: '#ef4444', // Red secondaryColor: '#64748b', // Slate fontFamily: 'sf-pro', fontSize: 'lg', glassEffect: true, borderRadius: 'xl' }; ``` ### Tailwind Config Presets Add these presets to your `tailwind.config.js`: ```js module.exports = { theme: { extend: { fontFamily: { 'inter': ['Inter', 'sans-serif'], 'sf-pro': ['-apple-system', 'BlinkMacSystemFont', 'SF Pro Display', 'sans-serif'], }, colors: { 'fireship-primary': 'var(--fireship-primary)', 'fireship-secondary': 'var(--fireship-secondary)', }, backdropBlur: { 'fireship': '20px', } } } } ``` ## SEO Features The package automatically generates: - **Meta Tags**: Title, description, keywords - **Open Graph**: og:title, og:description, og:image, og:type - **Twitter Cards**: twitter:card, twitter:title, twitter:description, twitter:image - **Structured Data**: JSON-LD for articles - **Canonical URLs**: Prevents duplicate content issues ## Analytics Integration Track various metrics: - **Page Views**: Automatic view tracking - **Engagement**: Likes, comments, shares - **Referrers**: Traffic sources - **Backlinks**: Incoming link discovery - **Performance**: Reading time, bounce rate ## Backlink Trading Network Participate in Fireship.ai's backlink trading network: 1. **Automatic Discovery**: Find relevant blogs in your niche 2. **Quality Scoring**: AI-powered relevance and authority scoring 3. **Trading Proposals**: Automated backlink exchange proposals 4. **Performance Tracking**: Monitor backlink impact on SEO ## TypeScript Support Full TypeScript support with comprehensive type definitions: ```tsx import type { BlogPost, ThemeSettings, BlogAnalytics, FireshipBlogProps } from 'fireship-blog'; const post: BlogPost = { id: '1', slug: 'my-post', title: 'My Blog Post', content: '# Hello World', // ... other required fields }; ``` ## Contributing 1. Fork the repository 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add some amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## License MIT License - see the [LICENSE](LICENSE) file for details. ## Support - 📧 Email: support@fireship.ai - 💬 Discord: [Fireship Community](https://discord.gg/fireship) - 📖 Documentation: [docs.fireship.ai](https://docs.fireship.ai) - 🐛 Issues: [GitHub Issues](https://github.com/fireship-io/fireship-blog/issues) ## Changelog ### v1.0.0 - Initial release - Core blog functionality - Admin dashboard - Analytics integration - Theme customization - SEO optimization - Backlink trading network