create-next-mdx-blog-app 2.2.7 β†’ 2.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +447 -441
  2. package/package.json +3 -3
package/README.md CHANGED
@@ -1,441 +1,447 @@
1
- # 🌟 Next-MDX-Blog-Starter
2
-
3
- A production-ready technical blog starter kit built with **Next.js (App Router)**, **MDX**, **Supabase**, and **TypeScript strict mode**. SSG-first for performance and SEO, with AI-powered reader features, an in-browser code sandbox, and a full content-management toolchain.
4
-
5
- **Live demo**: [next-mdx-blog-starter-sigma.vercel.app](https://next-mdx-blog-starter-sigma.vercel.app/)
6
-
7
- This project was developed with the help of **Claude** (Anthropic) and **Cursor**, with design inspiration from **Lovable**.
8
-
9
- ## πŸ“‘ Table of Contents
10
-
11
- - [Quick Start](#%EF%B8%8F-quick-start)
12
- - [Environment Variables](#-environment-variables)
13
- - [Architecture & Core Stack](#%EF%B8%8F-architecture--core-stack)
14
- - [MDX Content System](#-mdx-content-system)
15
- - [Custom MDX Components](#-custom-mdx-components)
16
- - [Reader Experience Features](#-reader-experience-features)
17
- - [AI Features](#-ai-features)
18
- - [Code Sandbox](#%EF%B8%8F-code-sandbox)
19
- - [Author Profile Pages](#-author-profile-pages)
20
- - [Search](#-search)
21
- - [Tags](#-tags)
22
- - [Newsletter Subscription](#-newsletter-subscription)
23
- - [Supabase Database](#%EF%B8%8F-supabase-database)
24
- - [Article Manager CLI](#%EF%B8%8F-article-manager-cli)
25
- - [Project Scripts](#-project-scripts)
26
- - [AWS S3 Image Storage](#%EF%B8%8F-aws-s3-image-storage)
27
- - [SEO: Sitemap & Robots](#%EF%B8%8F-seo-sitemap--robots)
28
- - [Mobile Responsiveness](#-mobile-responsiveness)
29
- - [Analytics](#-analytics)
30
- - [Docker](#-docker)
31
- - [Useful Links](#-useful-links)
32
-
33
- ## βš™οΈ Quick Start
34
-
35
- ### Prerequisites
36
- - **Node.js** 18.17.0 or later (NPM included)
37
-
38
- ### Option 1 β€” NPM installer (recommended)
39
-
40
- Scaffold the blog into an empty directory:
41
-
42
- ```bash
43
- npx create-next-mdx-blog-app .
44
- ```
45
-
46
- The installer ([`create-next-mdx-blog-app`](https://www.npmjs.com/package/create-next-mdx-blog-app/), v2.2.7, MIT) clones the app, installs dependencies, and prints the environment setup steps.
47
-
48
- ### Option 2 β€” Manual clone
49
-
50
- ```bash
51
- git clone https://github.com/CodingAbdullah/Next-MDX-Blog-Starter.git
52
- cd Next-MDX-Blog-Starter/mdx-medium-blog-post-provider
53
- npm install
54
- ```
55
-
56
- ### Configure and run
57
-
58
- ```bash
59
- cp .env.example .env.local # fill in your credentials (see table below)
60
- npm run dev
61
- ```
62
-
63
- ## πŸ” Environment Variables
64
-
65
- A `.env.example` file at the project root lists every key. Copy it to `.env.local` and fill in your values:
66
-
67
- ```bash
68
- cp .env.example .env.local
69
- ```
70
-
71
- ```bash
72
- # .env.local
73
-
74
- # Supabase β€” dynamic blog post fetching
75
- SUPABASE_URL=
76
- SUPABASE_ANON_KEY=
77
-
78
- # Anthropic β€” Blog Assistant chatbot + AI Article Summarizer
79
- ANTHROPIC_API_KEY=
80
-
81
- # Site β€” public base URL (sitemap, robots.txt, summarizer origin allow-list)
82
- NEXT_PUBLIC_SITE_URL=
83
-
84
- # GitHub β€” optional, for the <GitHubGist> component
85
- GITHUB_TOKEN=
86
- GITHUB_USERNAME=
87
- GIST_BASE_URL=
88
-
89
- # Resend β€” newsletter signup
90
- RESEND_API_KEY=
91
- RESEND_AUDIENCE_ID=
92
- ```
93
-
94
- ### Required
95
-
96
- | Variable | Used by |
97
- |---|---|
98
- | `SUPABASE_URL` | Dynamic blog post fetching (Supabase client) |
99
- | `SUPABASE_ANON_KEY` | Dynamic blog post fetching (Supabase client) |
100
- | `ANTHROPIC_API_KEY` | Blog Assistant chatbot (`/api/chat`) and AI Article Summarizer (`/api/summarize/[slug]`) |
101
- | `RESEND_API_KEY` | Newsletter signup β€” authenticates with the Resend API |
102
- | `RESEND_AUDIENCE_ID` | Newsletter signup β€” the Resend Audience new subscribers are added to |
103
-
104
- ### Optional (sensible defaults)
105
-
106
- | Variable | Used by | Default |
107
- |---|---|---|
108
- | `NEXT_PUBLIC_SITE_URL` | Sitemap, robots.txt, summarizer origin allow-list | `http://localhost:3000` |
109
- | `GITHUB_TOKEN` | `<GitHubGist>` GitHub API auth β€” raises rate limit from 60 to 5,000 req/hr | unauthenticated |
110
- | `GITHUB_USERNAME` | mdxgists.net URL construction | `CodingAbdullah` |
111
- | `GIST_BASE_URL` | mdxgists.net link base URL | `https://mdxgists.net` |
112
-
113
- > πŸ”’ **Never commit `.env` files.** They are git-ignored and excluded from Docker images via `.dockerignore`. Server-only secrets (Supabase keys, Anthropic and Resend API keys, GitHub token) are read exclusively in Server Components and Route Handlers β€” only `NEXT_PUBLIC_SITE_URL` is exposed to the browser.
114
-
115
- ## πŸ—οΈ Architecture & Core Stack
116
-
117
- This starter kit is **SSG-first**: Static Site Generation is preferred everywhere, with dynamic rendering used only where required.
118
-
119
- - **Pre-rendered pages**: Blog posts and content pages are statically generated at build time
120
- - **Server Components first**: Supabase is queried directly from React Server Components β€” no custom backend APIs
121
- - **SEO-ready**: Meta tags, structured data, and semantic HTML generated statically
122
- - **CDN-friendly**: Static output deploys to any CDN or static host
123
- - **Minimal client JS**: Core content rendering requires no client-side JavaScript
124
-
125
- | Layer | Technology |
126
- |---|---|
127
- | Framework | Next.js (App Router), React, TypeScript (strict mode) |
128
- | Content | MDX, `gray-matter`, `next-mdx-remote` |
129
- | Database | Supabase (`@supabase/supabase-js`) |
130
- | Image storage | AWS S3 (via Next `<Image>`) |
131
- | Styling / UI | Tailwind CSS, shadcn/ui, `lucide-react`, `class-variance-authority` |
132
- | AI | Vercel AI SDK (`ai`, `@ai-sdk/anthropic`, `@ai-sdk/react`), `zod` |
133
- | Code sandbox | `@codesandbox/sandpack-react` (JS/TS/HTML), Pyodide (Python), sql.js (SQL) |
134
- | Syntax highlighting | `react-syntax-highlighter` |
135
- | Email | Resend (`resend`) |
136
- | Notifications | `sonner` toasts |
137
- | Theming | `next-themes` |
138
- | Tooling | Docker, Vercel Analytics, `tsx`, `react-doctor` (`npm run doctor`) |
139
-
140
- ## 🌐 MDX Content System
141
-
142
- This project renders blog posts from `.mdx` files in two modes, each with an included example:
143
-
144
- - **Static MDX** β€” pre-rendered at build time. Route: `/sample-blog-post-page`, content: `src/markdown/ArticleContent.mdx`
145
- - **Dynamic MDX** β€” rendered on the server at request time via `next-mdx-remote`'s `MDXRemote` component. Route: `/dynamic/[dynamic_blog_post]`, content: `src/markdown/DynamicArticleContent.mdx`
146
-
147
- ### Frontmatter (article metadata)
148
-
149
- Each `.mdx` file carries metadata at the top of the file between `---` delimiters, parsed with `gray-matter`:
150
-
151
- ```yaml
152
- ---
153
- title: string
154
- description: string
155
- publishedAt: string
156
- author: string
157
- tags: string[]
158
- image: string
159
- ---
160
- ```
161
-
162
- ### The `mdx-components.tsx` file
163
-
164
- `mdx-components.tsx` at the project root styles built-in HTML elements and swaps `<img>` and `<a>` for the optimized Next.js `<Image>` and `<Link>` components. See the [Next.js docs](https://nextjs.org/docs/app/api-reference/file-conventions/mdx-components) for how this file convention works.
165
-
166
- ## 🧩 Custom MDX Components
167
-
168
- Custom components for MDX content live in `src/components/customMDXComponents/`.
169
-
170
- ### CodeBlock β€” syntax highlighting
171
-
172
- Highlights code blocks with `react-syntax-highlighter` (default theme: `vscDarkPlus` β€” [demo of available themes](https://react-syntax-highlighter.github.io/react-syntax-highlighter/demo/)). A **copy button** in the top-right corner writes the code to the clipboard and confirms via a sonner toast.
173
-
174
- ### GitHubGist β€” live gist embeds
175
-
176
- Embed public GitHub Gists directly in MDX:
177
-
178
- ```mdx
179
- <GitHubGist id="your-gist-id" figCaptionText="Caption shown below the gist" />
180
- ```
181
-
182
- **How it works:**
183
- 1. `GitHubGist` (an async Server Component) calls `https://api.github.com/gists/<id>` for metadata (file name, detected language), then fetches the raw content from the returned `raw_url`. Results are cached for one hour via Next.js ISR (`next: { revalidate: 3600 }`).
184
- 2. The language is mapped to a Prism-compatible token via `GITHUB_GIST_LANGUAGE_MAP` (`src/utils/constants/GitHubGistConstants.ts`) β€” 70+ languages supported, with sensible fallbacks (`language.toLowerCase()`, then `text`).
185
- 3. The code renders through `GistCodeBlock` inside a scrollable container with a custom green scrollbar.
186
-
187
- **Each gist header includes:** a language badge, a **Copy** button (with toast confirmation), and a link to the gist on [mdxgists.net](https://mdxgists.net) β€” a companion site for browsing and sharing MDX-ready gists. The URL is built as `<GIST_BASE_URL>/<GITHUB_USERNAME>/<gist-id>`; both values are overridable via environment variables.
188
-
189
- **Components:**
190
- - `GitHubGist.tsx` β€” async Server Component; fetching, language resolution, gist UI
191
- - `GistCodeBlock.tsx` β€” syntax-highlighted code display
192
- - `GistCopyButton.tsx` β€” client component; copy-to-clipboard + external link
193
-
194
- **GitHub token (optional but recommended):** unauthenticated GitHub API requests are limited to **60/hr per IP**. Set `GITHUB_TOKEN` in `.env.local` to raise this to **5,000/hr**. Generate one at GitHub β†’ Settings β†’ Developer settings β†’ Personal access tokens β€” the read-only `gist` scope (or no scopes for public gists) is sufficient.
195
-
196
- > Only **public** gists are supported by default; the component can be extended for private gists with appropriate token scopes.
197
-
198
- ### MDXImage β€” optimized images with captions
199
-
200
- Wraps the Next.js `<Image>` component with `<figure>`/`<figcaption>` for seamless captions, displayed in a styled container with a green glow border and hover scale effect consistent with the matrix-green design system.
201
-
202
- ## 🎨 Reader Experience Features
203
-
204
- | Feature | Component | Behaviour |
205
- |---|---|---|
206
- | **Light/dark mode** | `src/components/ThemeToggle.tsx` | Header toggle between dark (default) and light themes via `next-themes` (`ThemeProvider.tsx`); persisted to `localStorage`. `ThemedToaster.tsx` keeps sonner toasts theme-matched |
207
- | **Reading progress bar** | `src/components/ReadingProgressBar.tsx` | Thin green bar fixed to the top of article pages; passive scroll listener, `role="progressbar"` ARIA attributes |
208
- | **Back to top** | `src/components/BackToTopButton.tsx` | Floating button appears after 400px of scroll; smooth-scrolls to top |
209
- | **Copy link** | `src/components/CopyLinkButton.tsx` | Article-header button; copies the page URL with a brief icon-swap confirmation |
210
- | **Social share** | `src/components/SocialShareButtons.tsx` | Pre-filled share dialogs for X (Twitter), LinkedIn, and Reddit using the article title and URL |
211
- | **View counter** | `src/components/ViewCounter.tsx` | Live per-article view count in a Supabase `view_counts` table, incremented atomically via the `increment_view_count` RPC. Dynamic pages increment server-side; static pages call the `/api/views/[slug]` route after hydration |
212
- | **Related articles** | `src/components/RelatedArticles.tsx` | Shown at the bottom of every dynamic article; surfaces up to 5 other articles ranked by shared tags (then publish date) via `fetchRelatedArticles()` |
213
- | **Skip to content** | `src/components/SkipToContent.tsx` | Visually-hidden link at the very top of every page, revealed on keyboard focus, that jumps straight to `<main id="main-content">` β€” lets keyboard and screen-reader users bypass repeated header/nav on every route |
214
-
215
- ## πŸ€– AI Features
216
-
217
- Both AI features use **Claude Haiku** through the Vercel AI SDK and require `ANTHROPIC_API_KEY`.
218
-
219
- ### Blog Assistant Chatbot (`/chat`)
220
-
221
- An interactive AI chatbot optimised for readers of this technical blog.
222
-
223
- - **Streaming responses** via `TextStreamChatTransport` and an edge API route (`src/app/api/chat/route.ts`), which converts `UIMessages` with `convertToModelMessages` and streams via `streamText`
224
- - **Three blog-focused tools** available to the model:
225
- - `searchBlogTopics` β€” searches a curated list of topics covered by this blog (JS, TS, React, Next.js, MDX, Docker, AWS, etc.)
226
- - `getCodeExample` β€” generates a runnable code example for a concept and language
227
- - `explainConcept` β€” produces a brief or detailed technical explanation
228
- - **Ephemeral conversations** β€” nothing is persisted server-side; a "New Chat" button clears the session
229
- - **Tool calls rendered inline** in the message thread via `chat-tool-result.tsx`
230
-
231
- Configuration lives in `src/utils/constants/AiChatConfig.ts` (model, temperature, max tokens, system prompt) and `ToolConfig.ts` (tool icons/labels/colours). UI components are under `src/components/chat/` (`chat-interface.tsx`, `chat-messages.tsx`, `chat-input.tsx`, `chat-tool-result.tsx`).
232
-
233
- ### AI Article Summarizer
234
-
235
- A **Generate TL;DR** button above every dynamic article streams a short summary into a collapsible green panel.
236
-
237
- - Only the article **slug** is sent over the wire β€” `src/app/api/summarize/[slug]/route.ts` (edge) fetches the article server-side
238
- - Protected by an **origin allow-list** (`NEXT_PUBLIC_SITE_URL`), a **per-IP rate limit** (10/min), and a **1-hour in-memory cache** (written via `after()`)
239
- - The client (`src/components/ArticleSummarizer.tsx`) cancels in-flight requests with `AbortController` on close/unmount
240
- - Model and prompt configured in `src/utils/constants/AiSummaryConfig.ts`
241
-
242
- ## πŸ–₯️ Code Sandbox
243
-
244
- An interactive in-browser code execution environment at `/code-sandbox` spanning five languages β€” **JavaScript, TypeScript, HTML/CSS, Python, and SQL** β€” all executing **entirely client-side**; no code reaches the server.
245
-
246
- - **JavaScript & TypeScript** β€” powered by **Sandpack** (`@codesandbox/sandpack-react`); switch with one click and the editor reloads with a language-appropriate default snippet. Full editor with line numbers, inline TypeScript errors, and a live console panel side-by-side with the code.
247
- - **HTML/CSS** β€” also powered by Sandpack, using its `static` template for multi-file editing (`index.html` + `styles.css`) with tabbed files and a **live rendered preview** in place of the console.
248
- - **Python** β€” powered by **Pyodide** (CPython compiled to WebAssembly), loaded on demand from a version-pinned CDN and executed inside a dedicated **Web Worker** so the UI never blocks. `print()` output streams into a console panel line by line.
249
- - **SQL** β€” powered by **sql.js** (SQLite compiled to WebAssembly), also loaded from CDN and run inside its own Web Worker against a fresh in-memory database on every run. `SELECT` results render as a scrollable table; other statements (`CREATE`, `INSERT`, `UPDATE`) confirm with a row-count message.
250
- - **Quick Examples** β€” pre-loaded snippets per language (Fibonacci, Async/Await, Data Structures for JS; Types & Interfaces, Generics, Classes & OOP for TS; Responsive Card, Flexbox Layout, CSS Animation for HTML/CSS; Fibonacci, Data Structures, Classes & OOP for Python; Joins, Aggregation, Filtering & Sorting for SQL) defined in `src/utils/constants/SandboxExamples.ts`
251
- - **Consistent toolbar** across every language β€” Run, Copy, Download, and Reset β€” with a shared matrix-green theme and `JetBrains Mono` font
252
-
253
- Components: `src/components/SandpackEditor.tsx` (JS/TS/HTML β€” provider, editor, toolbar, console/preview), `PyodideSandbox.tsx` (Python), `SqlSandbox.tsx` (SQL), and `CodeSandboxFeaturesSection.tsx` (feature highlights grid). The Python and SQL runtimes ship as static Web Worker scripts in `public/workers/` (`pyodide-worker.js`, `sql-worker.js`) β€” kept outside the Next.js bundler since Pyodide's and sql.js's browser builds aren't reliably bundle-safe.
254
-
255
- ## πŸ‘₯ Author Profile Pages
256
-
257
- A `/authors` index lists every distinct contributor pulled from the Supabase `Article` table, with per-author profile routes at `/authors/[slug]` showing their bio, avatar, and every article they've published.
258
-
259
- ## πŸ” Search
260
-
261
- Full-text search across published articles at `/search`, powered by native Postgres `tsvector` β€” no external search service required.
262
-
263
- - **Search-as-you-type** β€” `src/components/ArticleSearch.tsx` debounces input (300 ms), cancels stale requests with `AbortController`, caches repeated queries, and waits for at least 2 characters before querying
264
- - **Prefix matching** β€” partial words match while you type (`reac` β†’ `react`)
265
- - **Ranked, weighted results** β€” scored by `ts_rank` with column weights (title > tags > description > content) and returned as lightweight summaries (the heavy `content` column is excluded)
266
- - **Request flow** β€” `GET /api/search?q=…` (`src/app/api/search/route.ts`) β†’ `searchArticles()` (`src/utils/functions/rpc/searchArticles.ts`) β†’ the `search_articles` Postgres RPC
267
-
268
- ### One-time setup
269
-
270
- Run **`scripts/sql/DDL/createSearchArticlesFunction.sql`** once in the Supabase SQL editor. It creates the weighted GIN index and the `search_articles` function. Search returns an error until this script is deployed.
271
-
272
- ### ⚠️ Change the hardcoded author filter
273
-
274
- The shipped function locks results to a single author:
275
-
276
- ```sql
277
- AND a."articleAuthorName" = 'Abdullah Muhammad.'
278
- ```
279
-
280
- Before deploying, replace `'Abdullah Muhammad.'` with **your own author name** β€” it must match the `articleAuthorName` values in your `Article` table **exactly**, including any trailing punctuation. Alternatively, **delete that line entirely** to search across all authors. Re-run the script after editing.
281
-
282
- ## 🏷 Tags
283
-
284
- Browse articles by topic at `/tags`, which lists every distinct tag pulled from the Supabase `Article` table, with per-tag archive pages at `/tags/[tag]`.
285
-
286
- - `fetchAllTags()` (`src/utils/functions/tags/fetchAllTags.ts`) β€” deduplicates tags case-insensitively and counts how many articles carry each one
287
- - `fetchArticlesByTag()` (`src/utils/functions/crud/fetchArticlesByTag.ts`) β€” returns every article carrying a given tag, newest first
288
- - `slugifyTag()` (`src/utils/functions/tags/slugifyTag.ts`) β€” normalizes tag names into URL-safe slugs (e.g. `"DevOps"` β†’ `"devops"`), so casing/spacing variants still resolve to the same tag page
289
-
290
- ## πŸ“¬ Newsletter Subscription
291
-
292
- An integrated newsletter signup form powered by [Resend](https://resend.com). Visitors can subscribe from the home page or the bottom of any article; new subscribers are added to a Resend **Audience** and receive a welcome email.
293
-
294
- ### Components & routes
295
- - `src/components/NewsletterSignup.tsx` β€” reusable client component with `matrix` (article pages) and `neutral` (home page) visual variants
296
- - `src/app/api/newsletter/subscribe/route.ts` β€” Node-runtime POST handler; validates the email with Zod
297
- - `src/utils/functions/newsletter/subscribeToNewsletter.ts` β€” adds the contact to your Audience and triggers the welcome email
298
- - `src/utils/functions/newsletter/welcomeEmailTemplate.ts` β€” subject + HTML/text bodies
299
- - `src/utils/functions/resend_client/ResendClient.ts` β€” server-only Resend client factory
300
-
301
- ### Setup
302
- 1. Create a Resend account at [resend.com](https://resend.com)
303
- 2. **API key** β€” API Keys β†’ Create API Key with **Sending** and **Audiences** access β†’ set `RESEND_API_KEY`
304
- 3. **Audience** β€” Audiences β†’ Create Audience β†’ copy the UUID into `RESEND_AUDIENCE_ID`
305
- 4. Restart `npm run dev` so Next.js picks up the new variables
306
-
307
- ### ⚠️ ***Important: a verified sending domain on Resend is required for email delivery to real subscribers.***
308
-
309
- Out of the box the welcome email is sent from **`onboarding@resend.dev`**, Resend's sandbox sender, which **only delivers to the email address that owns your Resend account**.
310
-
311
- > 🚨 ***You MUST verify your own sending domain (Resend dashboard β†’ Domains β†’ Add Domain, then complete the SPF/DKIM DNS records) before the newsletter can deliver welcome emails to real subscribers.*** Once verified, update the `WELCOME_EMAIL_FROM` constant in `src/utils/functions/newsletter/subscribeToNewsletter.ts` to an address on that domain (e.g. `newsletter@yourdomain.com`).
312
-
313
- If the domain step is skipped, the contact is still added to your Audience, but the welcome email silently fails (logged server-side as `[newsletter] Resend emails.send returned an error: ...`).
314
-
315
- ## πŸ—„οΈ Supabase Database
316
-
317
- Supabase is integrated **directly in Server Components** β€” no custom backend API layer. The client factory lives in `src/utils/functions/supabase_client/`.
318
-
319
- - **CRUD functions** β€” `src/utils/functions/crud/` (create, read, update, delete articles)
320
- - **RPC functions** β€” `src/utils/functions/rpc/` (e.g. `incrementViewCount`)
321
- - **SQL scripts** β€” `scripts/sql/DDL/` (create/alter/drop tables, view-counts table, RPC function) and `scripts/sql/DML/` (insert/fetch/update/delete article statements)
322
-
323
- **Ensure your Supabase Row Level Security policies allow the CRUD actions you need** β€” these are configured in the Supabase console.
324
-
325
- Shared constants, helper functions, and TypeScript types live under `src/utils/` (`constants/`, `functions/`, `types/`). Some constants serve as placeholders for this demo application.
326
-
327
- ## ⌨️ Article Manager CLI
328
-
329
- `scripts/action-script/article-manager.ts` manages articles in Supabase from the command line using the CRUD functions above, run via `tsx` (no TypeScript build config needed):
330
-
331
- ```bash
332
- # Insert an article into Supabase
333
- npx tsx article-manager.ts insert article-slug
334
-
335
- # Delete an article
336
- npx tsx article-manager.ts delete article-slug
337
-
338
- # Update an article
339
- npx tsx article-manager.ts update article-slug new-article-file
340
-
341
- # Fetch a single article
342
- npx tsx article-manager.ts fetch article-slug
343
-
344
- # Fetch all articles
345
- npx tsx article-manager.ts fetchAll
346
- ```
347
-
348
- The **article slug** is the name of the markdown file in `src/markdown/` minus the `.mdx` extension. The `update` command's second argument follows the same convention.
349
-
350
- ## πŸ“œ Project Scripts
351
-
352
- The `/scripts` folder contains tooling for project and database setup:
353
-
354
- - **`scripts/sql/`** β€” DDL and DML statements for initializing and populating the database
355
- - **`scripts/powershell/`** β€” Windows setup plus bulk article/S3 helpers (`project_setup.ps1`, `bulk-create-articles.ps1`, `bulk-update-articles.ps1`, `bulk-s3-folder-creation.ps1`, `create-missing-mdx-files.ps1`)
356
- - **`scripts/bash/`** β€” the same toolkit for Linux/macOS
357
- - **`scripts/action-script/`** β€” the Article Manager CLI (above)
358
- - **`scripts/github-gist-fetcher/`** β€” fetches a public gist's raw content to `src/github_gists/<gist-id>.txt`:
359
- ```bash
360
- npx tsx scripts/github-gist-fetcher/fetch-github-gist.ts <gist-id>
361
- ```
362
- > **Note:** no longer required for rendering β€” `<GitHubGist>` fetches live from the GitHub API. Retained for offline inspection or local caching workflows.
363
-
364
- ## 🌩️ AWS S3 Image Storage
365
-
366
- Images referenced in `.mdx` files (via the `MDXImage` component) are served from AWS S3. The allowed external image domain is configured in `next.config.ts` β€” point it at your own bucket, or swap in another storage service entirely.
367
-
368
- ## πŸ—ΊοΈ SEO: Sitemap & Robots
369
-
370
- - **`sitemap.xml`** β€” auto-generated at build time by `src/app/sitemap.ts`, covering all static routes and every dynamic article slug fetched from Supabase
371
- - **`robots.txt`** β€” served from `src/app/robots.ts`, permitting all crawlers and pointing them at the sitemap
372
-
373
- Both use `NEXT_PUBLIC_SITE_URL` as the base URL.
374
-
375
- ## πŸ“± Mobile Responsiveness
376
-
377
- All components are built mobile-first with Tailwind responsive prefixes (`sm:`, `md:`, `lg:`). Key behaviours:
378
-
379
- | Component | Mobile behaviour |
380
- |---|---|
381
- | `ArticleHeader` | Title scales `text-2xl` β†’ `text-4xl`; author row stacks vertically |
382
- | `ArticleAuthorBio` | Avatar and text stack vertically; full-width button; center-aligned text |
383
- | `GitHubGist` | Header wraps via `flex-wrap`; code scrolls horizontally with a styled green scrollbar |
384
- | `CodeBlock` | Copy button absolutely positioned, never interferes with code flow |
385
- | `MDXImage` | Container scales inline; hover effect on capable devices |
386
- | Chat & Code Sandbox | Responsive padding and height calculations across breakpoints |
387
-
388
- The root layout exports a `viewport` configuration (Next.js `Viewport` type) for correct scaling on all mobile browsers:
389
-
390
- ```ts
391
- export const viewport: Viewport = {
392
- width: 'device-width',
393
- initialScale: 1,
394
- };
395
- ```
396
-
397
- ## πŸ“Š Analytics
398
-
399
- Vercel Analytics (`@vercel/analytics`) is integrated to track user interactions and performance metrics β€” kept lightweight and non-blocking.
400
-
401
- ## 🐳 Docker
402
-
403
- A multi-stage `Dockerfile` at the project root produces a production image with environment variables injected at runtime:
404
-
405
- ```bash
406
- docker build -t mdx-medium-blog .
407
- ```
408
-
409
- ```bash
410
- docker run \
411
- -e SUPABASE_URL=your_supabase_url \
412
- -e SUPABASE_ANON_KEY=your_supabase_anon_key \
413
- -e ANTHROPIC_API_KEY=your_anthropic_api_key \
414
- -e NEXT_PUBLIC_SITE_URL=https://yourdomain.com \
415
- -e GITHUB_TOKEN=your_github_token \
416
- -e GITHUB_USERNAME=your_github_username \
417
- -e GIST_BASE_URL=https://mdxgists.net \
418
- -e RESEND_API_KEY=your_resend_api_key \
419
- -e RESEND_AUDIENCE_ID=your_resend_audience_id \
420
- -p 3000:3000 mdx-medium-blog
421
- ```
422
-
423
- The project also remains compatible with **Vercel** and pure **static hosting** (SSG mode).
424
-
425
- ## πŸ”— Useful Links
426
-
427
- - [Next.js Documentation](https://nextjs.org/docs)
428
- - [MDX Documentation](https://mdxjs.com/docs/)
429
- - [Lee Robinson's Next.js + MDX Tutorial Video](https://www.youtube.com/watch?v=34bRv6cQezo&ab_channel=leerob)
430
- - [MDX Playground](https://mdxjs.com/playground/)
431
- - [React Documentation](https://react.dev/)
432
- - [Supabase Documentation](https://supabase.com/docs)
433
- - [Docker Documentation](https://docs.docker.com/)
434
- - [React Syntax Highlighter](https://github.com/react-syntax-highlighter/react-syntax-highlighter)
435
- - [Sandpack Documentation](https://sandpack.codesandbox.io/docs)
436
- - [Pyodide Documentation](https://pyodide.org/en/stable/)
437
- - [sql.js Documentation](https://sql.js.org/documentation/)
438
- - [Vercel AI SDK Documentation](https://sdk.vercel.ai/docs)
439
- - [Anthropic AI SDK Provider](https://sdk.vercel.ai/providers/ai-sdk-providers/anthropic)
440
- - [Resend Documentation](https://resend.com/docs)
441
- - [Zod Documentation](https://zod.dev)
1
+ # 🌟 Next-MDX-Blog-Starter
2
+
3
+ A production-ready technical blog starter kit built with **Next.js (App Router)**, **MDX**, **Supabase**, and **TypeScript strict mode**. SSG-first for performance and SEO, with AI-powered reader features, an in-browser code sandbox, and a full content-management toolchain.
4
+
5
+ **Live demo**: [next-mdx-blog-starter-sigma.vercel.app](https://next-mdx-blog-starter-sigma.vercel.app/)
6
+
7
+ This project was developed with the help of **Claude** (Anthropic) and **Cursor**, with design inspiration from **Lovable**.
8
+
9
+ ## πŸ“‘ Table of Contents
10
+
11
+ - [Quick Start](#%EF%B8%8F-quick-start)
12
+ - [Environment Variables](#-environment-variables)
13
+ - [Architecture & Core Stack](#%EF%B8%8F-architecture--core-stack)
14
+ - [MDX Content System](#-mdx-content-system)
15
+ - [Custom MDX Components](#-custom-mdx-components)
16
+ - [Reader Experience Features](#-reader-experience-features)
17
+ - [AI Features](#-ai-features)
18
+ - [Code Sandbox](#%EF%B8%8F-code-sandbox)
19
+ - [Author Profile Pages](#-author-profile-pages)
20
+ - [Search](#-search)
21
+ - [Tags](#-tags)
22
+ - [Newsletter Subscription](#-newsletter-subscription)
23
+ - [Supabase Database](#%EF%B8%8F-supabase-database)
24
+ - [Article Manager CLI](#%EF%B8%8F-article-manager-cli)
25
+ - [Project Scripts](#-project-scripts)
26
+ - [AWS S3 Image Storage](#%EF%B8%8F-aws-s3-image-storage)
27
+ - [SEO: Sitemap, Robots & Structured Data](#%EF%B8%8F-seo-sitemap-robots--structured-data)
28
+ - [Mobile Responsiveness](#-mobile-responsiveness)
29
+ - [Analytics](#-analytics)
30
+ - [Docker](#-docker)
31
+ - [Useful Links](#-useful-links)
32
+
33
+ ## βš™οΈ Quick Start
34
+
35
+ ### Prerequisites
36
+ - **Node.js** 18.17.0 or later (NPM included)
37
+
38
+ ### Option 1 β€” NPM installer (recommended)
39
+
40
+ Scaffold the blog into an empty directory:
41
+
42
+ ```bash
43
+ npx create-next-mdx-blog-app .
44
+ ```
45
+
46
+ The installer ([`create-next-mdx-blog-app`](https://www.npmjs.com/package/create-next-mdx-blog-app/), v2.2.9, MIT) clones the app, installs dependencies, and prints the environment setup steps.
47
+
48
+ ### Option 2 β€” Manual clone
49
+
50
+ ```bash
51
+ git clone https://github.com/CodingAbdullah/Next-MDX-Blog-Starter.git
52
+ cd Next-MDX-Blog-Starter/mdx-medium-blog-post-provider
53
+ npm install
54
+ ```
55
+
56
+ ### Configure and run
57
+
58
+ ```bash
59
+ cp .env.example .env.local # fill in your credentials (see table below)
60
+ npm run dev
61
+ ```
62
+
63
+ ## πŸ” Environment Variables
64
+
65
+ A `.env.example` file at the project root lists every key. Copy it to `.env.local` and fill in your values:
66
+
67
+ ```bash
68
+ cp .env.example .env.local
69
+ ```
70
+
71
+ ```bash
72
+ # .env.local
73
+
74
+ # Supabase β€” dynamic blog post fetching
75
+ SUPABASE_URL=
76
+ SUPABASE_ANON_KEY=
77
+
78
+ # Anthropic β€” Blog Assistant chatbot + AI Article Summarizer
79
+ ANTHROPIC_API_KEY=
80
+
81
+ # Site β€” public base URL (sitemap, robots.txt, summarizer origin allow-list)
82
+ NEXT_PUBLIC_SITE_URL=
83
+
84
+ # GitHub β€” optional, for the <GitHubGist> component
85
+ GITHUB_TOKEN=
86
+ GITHUB_USERNAME=
87
+ GIST_BASE_URL=
88
+
89
+ # Resend β€” newsletter signup
90
+ RESEND_API_KEY=
91
+ RESEND_AUDIENCE_ID=
92
+ ```
93
+
94
+ ### Required
95
+
96
+ | Variable | Used by |
97
+ |---|---|
98
+ | `SUPABASE_URL` | Dynamic blog post fetching (Supabase client) |
99
+ | `SUPABASE_ANON_KEY` | Dynamic blog post fetching (Supabase client) |
100
+ | `ANTHROPIC_API_KEY` | Blog Assistant chatbot (`/api/chat`) and AI Article Summarizer (`/api/summarize/[slug]`) |
101
+ | `RESEND_API_KEY` | Newsletter signup β€” authenticates with the Resend API |
102
+ | `RESEND_AUDIENCE_ID` | Newsletter signup β€” the Resend Audience new subscribers are added to |
103
+
104
+ ### Optional (sensible defaults)
105
+
106
+ | Variable | Used by | Default |
107
+ |---|---|---|
108
+ | `NEXT_PUBLIC_SITE_URL` | Sitemap, robots.txt, RSS feed, JSON-LD structured data, summarizer origin allow-list | `http://localhost:3000` |
109
+ | `GITHUB_TOKEN` | `<GitHubGist>` GitHub API auth β€” raises rate limit from 60 to 5,000 req/hr | unauthenticated |
110
+ | `GITHUB_USERNAME` | mdxgists.net URL construction | `CodingAbdullah` |
111
+ | `GIST_BASE_URL` | mdxgists.net link base URL | `https://mdxgists.net` |
112
+
113
+ > πŸ”’ **Never commit `.env` files.** They are git-ignored and excluded from Docker images via `.dockerignore`. Server-only secrets (Supabase keys, Anthropic and Resend API keys, GitHub token) are read exclusively in Server Components and Route Handlers β€” only `NEXT_PUBLIC_SITE_URL` is exposed to the browser.
114
+
115
+ ## πŸ—οΈ Architecture & Core Stack
116
+
117
+ This starter kit is **SSG-first**: Static Site Generation is preferred everywhere, with dynamic rendering used only where required.
118
+
119
+ - **Pre-rendered pages**: Blog posts and content pages are statically generated at build time
120
+ - **Server Components first**: Supabase is queried directly from React Server Components β€” no custom backend APIs
121
+ - **SEO-ready**: Meta tags, structured data, and semantic HTML generated statically
122
+ - **CDN-friendly**: Static output deploys to any CDN or static host
123
+ - **Minimal client JS**: Core content rendering requires no client-side JavaScript
124
+
125
+ | Layer | Technology |
126
+ |---|---|
127
+ | Framework | Next.js (App Router), React, TypeScript (strict mode) |
128
+ | Content | MDX, `gray-matter`, `next-mdx-remote` |
129
+ | Database | Supabase (`@supabase/supabase-js`) |
130
+ | Image storage | AWS S3 (via Next `<Image>`) |
131
+ | Styling / UI | Tailwind CSS, shadcn/ui, `lucide-react`, `class-variance-authority` |
132
+ | AI | Vercel AI SDK (`ai`, `@ai-sdk/anthropic`, `@ai-sdk/react`), `zod` |
133
+ | Code sandbox | `@codesandbox/sandpack-react` (JS/TS/HTML), Pyodide (Python), sql.js (SQL) |
134
+ | Syntax highlighting | `react-syntax-highlighter` |
135
+ | Email | Resend (`resend`) |
136
+ | Notifications | `sonner` toasts |
137
+ | Theming | `next-themes` |
138
+ | Tooling | Docker, Vercel Analytics, `tsx`, `react-doctor` (`npm run doctor`) |
139
+
140
+ ## 🌐 MDX Content System
141
+
142
+ This project renders blog posts from `.mdx` files in two modes, each with an included example:
143
+
144
+ - **Static MDX** β€” pre-rendered at build time. Route: `/sample-blog-post-page`, content: `src/markdown/ArticleContent.mdx`
145
+ - **Dynamic MDX** β€” rendered on the server at request time via `next-mdx-remote`'s `MDXRemote` component. Route: `/dynamic/[dynamic_blog_post]`, content: `src/markdown/DynamicArticleContent.mdx`
146
+
147
+ ### Frontmatter (article metadata)
148
+
149
+ Each `.mdx` file carries metadata at the top of the file between `---` delimiters, parsed with `gray-matter`:
150
+
151
+ ```yaml
152
+ ---
153
+ title: string
154
+ description: string
155
+ publishedAt: string
156
+ author: string
157
+ tags: string[]
158
+ image: string
159
+ ---
160
+ ```
161
+
162
+ ### The `mdx-components.tsx` file
163
+
164
+ `mdx-components.tsx` at the project root styles built-in HTML elements and swaps `<img>` and `<a>` for the optimized Next.js `<Image>` and `<Link>` components. See the [Next.js docs](https://nextjs.org/docs/app/api-reference/file-conventions/mdx-components) for how this file convention works.
165
+
166
+ ## 🧩 Custom MDX Components
167
+
168
+ Custom components for MDX content live in `src/components/customMDXComponents/`.
169
+
170
+ ### CodeBlock β€” syntax highlighting
171
+
172
+ Highlights code blocks with `react-syntax-highlighter` (default theme: `vscDarkPlus` β€” [demo of available themes](https://react-syntax-highlighter.github.io/react-syntax-highlighter/demo/)). A **copy button** in the top-right corner writes the code to the clipboard and confirms via a sonner toast.
173
+
174
+ ### GitHubGist β€” live gist embeds
175
+
176
+ Embed public GitHub Gists directly in MDX:
177
+
178
+ ```mdx
179
+ <GitHubGist id="your-gist-id" figCaptionText="Caption shown below the gist" />
180
+ ```
181
+
182
+ **How it works:**
183
+ 1. `GitHubGist` (an async Server Component) calls `https://api.github.com/gists/<id>` for metadata (file name, detected language), then fetches the raw content from the returned `raw_url`. Results are cached for one hour via Next.js ISR (`next: { revalidate: 3600 }`).
184
+ 2. The language is mapped to a Prism-compatible token via `GITHUB_GIST_LANGUAGE_MAP` (`src/utils/constants/GitHubGistConstants.ts`) β€” 70+ languages supported, with sensible fallbacks (`language.toLowerCase()`, then `text`).
185
+ 3. The code renders through `GistCodeBlock` inside a scrollable container with a custom green scrollbar.
186
+
187
+ **Each gist header includes:** a language badge, a **Copy** button (with toast confirmation), and a link to the gist on [mdxgists.net](https://mdxgists.net) β€” a companion site for browsing and sharing MDX-ready gists. The URL is built as `<GIST_BASE_URL>/<GITHUB_USERNAME>/<gist-id>`; both values are overridable via environment variables.
188
+
189
+ **Components:**
190
+ - `GitHubGist.tsx` β€” async Server Component; fetching, language resolution, gist UI
191
+ - `GistCodeBlock.tsx` β€” syntax-highlighted code display
192
+ - `GistCopyButton.tsx` β€” client component; copy-to-clipboard + external link
193
+
194
+ **GitHub token (optional but recommended):** unauthenticated GitHub API requests are limited to **60/hr per IP**. Set `GITHUB_TOKEN` in `.env.local` to raise this to **5,000/hr**. Generate one at GitHub β†’ Settings β†’ Developer settings β†’ Personal access tokens β€” the read-only `gist` scope (or no scopes for public gists) is sufficient.
195
+
196
+ > Only **public** gists are supported by default; the component can be extended for private gists with appropriate token scopes.
197
+
198
+ ### MDXImage β€” optimized images with captions
199
+
200
+ Wraps the Next.js `<Image>` component with `<figure>`/`<figcaption>` for seamless captions, displayed in a styled container with a green glow border and hover scale effect consistent with the matrix-green design system.
201
+
202
+ ## 🎨 Reader Experience Features
203
+
204
+ | Feature | Component | Behaviour |
205
+ |---|---|---|
206
+ | **Light/dark mode** | `src/components/ThemeToggle.tsx` | Header toggle between dark (default) and light themes via `next-themes` (`ThemeProvider.tsx`); persisted to `localStorage`. `ThemedToaster.tsx` keeps sonner toasts theme-matched |
207
+ | **Reading progress bar** | `src/components/ReadingProgressBar.tsx` | Thin green bar fixed to the top of article pages; passive scroll listener, `role="progressbar"` ARIA attributes |
208
+ | **Back to top** | `src/components/BackToTopButton.tsx` | Floating button appears after 400px of scroll; smooth-scrolls to top |
209
+ | **Copy link** | `src/components/CopyLinkButton.tsx` | Article-header button; copies the page URL with a brief icon-swap confirmation |
210
+ | **Social share** | `src/components/SocialShareButtons.tsx` | Pre-filled share dialogs for X (Twitter), LinkedIn, and Reddit using the article title and URL |
211
+ | **View counter** | `src/components/ViewCounter.tsx` | Live per-article view count in a Supabase `view_counts` table, incremented atomically via the `increment_view_count` RPC. Dynamic pages increment server-side; static pages call the `/api/views/[slug]` route after hydration |
212
+ | **Related articles** | `src/components/RelatedArticles.tsx` | Shown at the bottom of every dynamic article; surfaces up to 5 other articles ranked by shared tags (then publish date) via `fetchRelatedArticles()` |
213
+ | **Skip to content** | `src/components/SkipToContent.tsx` | Visually-hidden link at the very top of every page, revealed on keyboard focus, that jumps straight to `<main id="main-content">` β€” lets keyboard and screen-reader users bypass repeated header/nav on every route |
214
+ | **High contrast mode** | `src/components/ContrastToggle.tsx` | Header toggle next to the theme switch; sets `data-contrast="high"` on `<html>` for solid, higher-contrast colours in both themes. Persisted in `localStorage`, applied before first paint (`ContrastScript.tsx`), and defaults to the OS `prefers-contrast: more` setting |
215
+
216
+ ## πŸ€– AI Features
217
+
218
+ Both AI features use **Claude Haiku** through the Vercel AI SDK and require `ANTHROPIC_API_KEY`.
219
+
220
+ ### Blog Assistant Chatbot (`/chat`)
221
+
222
+ An interactive AI chatbot optimised for readers of this technical blog.
223
+
224
+ - **Streaming responses** via `TextStreamChatTransport` and an edge API route (`src/app/api/chat/route.ts`), which converts `UIMessages` with `convertToModelMessages` and streams via `streamText`
225
+ - **Three blog-focused tools** available to the model:
226
+ - `searchBlogTopics` β€” searches a curated list of topics covered by this blog (JS, TS, React, Next.js, MDX, Docker, AWS, etc.)
227
+ - `getCodeExample` β€” generates a runnable code example for a concept and language
228
+ - `explainConcept` β€” produces a brief or detailed technical explanation
229
+ - **Ephemeral conversations** β€” nothing is persisted server-side; a "New Chat" button clears the session
230
+ - **Tool calls rendered inline** in the message thread via `chat-tool-result.tsx`
231
+
232
+ Configuration lives in `src/utils/constants/AiChatConfig.ts` (model, temperature, max tokens, system prompt) and `ToolConfig.ts` (tool icons/labels/colours). UI components are under `src/components/chat/` (`chat-interface.tsx`, `chat-messages.tsx`, `chat-input.tsx`, `chat-tool-result.tsx`).
233
+
234
+ ### AI Article Summarizer
235
+
236
+ A **Generate TL;DR** button above every dynamic article streams a short summary into a collapsible green panel.
237
+
238
+ - Only the article **slug** is sent over the wire β€” `src/app/api/summarize/[slug]/route.ts` (edge) fetches the article server-side
239
+ - Protected by an **origin allow-list** (`NEXT_PUBLIC_SITE_URL`), a **per-IP rate limit** (10/min), and a **1-hour in-memory cache** (written via `after()`)
240
+ - The client (`src/components/ArticleSummarizer.tsx`) cancels in-flight requests with `AbortController` on close/unmount
241
+ - Model and prompt configured in `src/utils/constants/AiSummaryConfig.ts`
242
+
243
+ ## πŸ–₯️ Code Sandbox
244
+
245
+ An interactive in-browser code execution environment at `/code-sandbox` spanning five languages β€” **JavaScript, TypeScript, HTML/CSS, Python, and SQL** β€” all executing **entirely client-side**; no code reaches the server.
246
+
247
+ - **JavaScript & TypeScript** β€” powered by **Sandpack** (`@codesandbox/sandpack-react`); switch with one click and the editor reloads with a language-appropriate default snippet. Full editor with line numbers, inline TypeScript errors, and a live console panel side-by-side with the code.
248
+ - **HTML/CSS** β€” also powered by Sandpack, using its `static` template for multi-file editing (`index.html` + `styles.css`) with tabbed files and a **live rendered preview** in place of the console.
249
+ - **Python** β€” powered by **Pyodide** (CPython compiled to WebAssembly), loaded on demand from a version-pinned CDN and executed inside a dedicated **Web Worker** so the UI never blocks. `print()` output streams into a console panel line by line.
250
+ - **SQL** β€” powered by **sql.js** (SQLite compiled to WebAssembly), also loaded from CDN and run inside its own Web Worker against a fresh in-memory database on every run. `SELECT` results render as a scrollable table; other statements (`CREATE`, `INSERT`, `UPDATE`) confirm with a row-count message.
251
+ - **Quick Examples** β€” pre-loaded snippets per language (Fibonacci, Async/Await, Data Structures for JS; Types & Interfaces, Generics, Classes & OOP for TS; Responsive Card, Flexbox Layout, CSS Animation for HTML/CSS; Fibonacci, Data Structures, Classes & OOP for Python; Joins, Aggregation, Filtering & Sorting for SQL) defined in `src/utils/constants/SandboxExamples.ts`
252
+ - **Consistent toolbar** across every language β€” Run, Copy, Download, and Reset β€” with a shared matrix-green theme and `JetBrains Mono` font
253
+
254
+ Components: `src/components/SandpackEditor.tsx` (JS/TS/HTML β€” provider, editor, toolbar, console/preview), `PyodideSandbox.tsx` (Python), `SqlSandbox.tsx` (SQL), and `CodeSandboxFeaturesSection.tsx` (feature highlights grid). The Python and SQL runtimes ship as static Web Worker scripts in `public/workers/` (`pyodide-worker.js`, `sql-worker.js`) β€” kept outside the Next.js bundler since Pyodide's and sql.js's browser builds aren't reliably bundle-safe.
255
+
256
+ ## πŸ‘₯ Author Profile Pages
257
+
258
+ A `/authors` index lists every distinct contributor pulled from the Supabase `Article` table, with per-author profile routes at `/authors/[slug]` showing their bio, avatar, and every article they've published.
259
+
260
+ ## πŸ” Search
261
+
262
+ Full-text search across published articles at `/search`, powered by native Postgres `tsvector` β€” no external search service required.
263
+
264
+ - **Search-as-you-type** β€” `src/components/ArticleSearch.tsx` debounces input (300 ms), cancels stale requests with `AbortController`, caches repeated queries, and waits for at least 2 characters before querying
265
+ - **Prefix matching** β€” partial words match while you type (`reac` β†’ `react`)
266
+ - **Ranked, weighted results** β€” scored by `ts_rank` with column weights (title > tags > description > content) and returned as lightweight summaries (the heavy `content` column is excluded)
267
+ - **Request flow** β€” `GET /api/search?q=…` (`src/app/api/search/route.ts`) β†’ `searchArticles()` (`src/utils/functions/rpc/searchArticles.ts`) β†’ the `search_articles` Postgres RPC
268
+
269
+ ### One-time setup
270
+
271
+ Run **`scripts/sql/DDL/createSearchArticlesFunction.sql`** once in the Supabase SQL editor. It creates the weighted GIN index and the `search_articles` function. Search returns an error until this script is deployed.
272
+
273
+ ### ⚠️ Change the hardcoded author filter
274
+
275
+ The shipped function locks results to a single author:
276
+
277
+ ```sql
278
+ AND a."articleAuthorName" = 'Abdullah Muhammad.'
279
+ ```
280
+
281
+ Before deploying, replace `'Abdullah Muhammad.'` with **your own author name** β€” it must match the `articleAuthorName` values in your `Article` table **exactly**, including any trailing punctuation. Alternatively, **delete that line entirely** to search across all authors. Re-run the script after editing.
282
+
283
+ ## 🏷 Tags
284
+
285
+ Browse articles by topic at `/tags`, which lists every distinct tag pulled from the Supabase `Article` table, with per-tag archive pages at `/tags/[tag]`.
286
+
287
+ - `fetchAllTags()` (`src/utils/functions/tags/fetchAllTags.ts`) β€” deduplicates tags case-insensitively and counts how many articles carry each one
288
+ - `fetchArticlesByTag()` (`src/utils/functions/crud/fetchArticlesByTag.ts`) β€” returns every article carrying a given tag, newest first
289
+ - `slugifyTag()` (`src/utils/functions/tags/slugifyTag.ts`) β€” normalizes tag names into URL-safe slugs (e.g. `"DevOps"` β†’ `"devops"`), so casing/spacing variants still resolve to the same tag page
290
+
291
+ ## πŸ“¬ Newsletter Subscription
292
+
293
+ An integrated newsletter signup form powered by [Resend](https://resend.com). Visitors can subscribe from the home page or the bottom of any article; new subscribers are added to a Resend **Audience** and receive a welcome email.
294
+
295
+ ### Components & routes
296
+ - `src/components/NewsletterSignup.tsx` β€” reusable client component with `matrix` (article pages) and `neutral` (home page) visual variants
297
+ - `src/app/api/newsletter/subscribe/route.ts` β€” Node-runtime POST handler; validates the email with Zod
298
+ - `src/utils/functions/newsletter/subscribeToNewsletter.ts` β€” adds the contact to your Audience and triggers the welcome email
299
+ - `src/utils/functions/newsletter/welcomeEmailTemplate.ts` β€” subject + HTML/text bodies
300
+ - `src/utils/functions/resend_client/ResendClient.ts` β€” server-only Resend client factory
301
+
302
+ ### Setup
303
+ 1. Create a Resend account at [resend.com](https://resend.com)
304
+ 2. **API key** β€” API Keys β†’ Create API Key with **Sending** and **Audiences** access β†’ set `RESEND_API_KEY`
305
+ 3. **Audience** β€” Audiences β†’ Create Audience β†’ copy the UUID into `RESEND_AUDIENCE_ID`
306
+ 4. Restart `npm run dev` so Next.js picks up the new variables
307
+
308
+ ### ⚠️ ***Important: a verified sending domain on Resend is required for email delivery to real subscribers.***
309
+
310
+ Out of the box the welcome email is sent from **`onboarding@resend.dev`**, Resend's sandbox sender, which **only delivers to the email address that owns your Resend account**.
311
+
312
+ > 🚨 ***You MUST verify your own sending domain (Resend dashboard β†’ Domains β†’ Add Domain, then complete the SPF/DKIM DNS records) before the newsletter can deliver welcome emails to real subscribers.*** Once verified, update the `WELCOME_EMAIL_FROM` constant in `src/utils/functions/newsletter/subscribeToNewsletter.ts` to an address on that domain (e.g. `newsletter@yourdomain.com`).
313
+
314
+ If the domain step is skipped, the contact is still added to your Audience, but the welcome email silently fails (logged server-side as `[newsletter] Resend emails.send returned an error: ...`).
315
+
316
+ ## πŸ—„οΈ Supabase Database
317
+
318
+ Supabase is integrated **directly in Server Components** β€” no custom backend API layer. The client factory lives in `src/utils/functions/supabase_client/`.
319
+
320
+ - **CRUD functions** β€” `src/utils/functions/crud/` (create, read, update, delete articles)
321
+ - **RPC functions** β€” `src/utils/functions/rpc/` (e.g. `incrementViewCount`)
322
+ - **SQL scripts** β€” `scripts/sql/DDL/` (create/alter/drop tables, view-counts table, RPC functions, `updated_at` trigger) and `scripts/sql/DML/` (insert/fetch/update/delete article statements)
323
+
324
+ **Ensure your Supabase Row Level Security policies allow the CRUD actions you need** β€” these are configured in the Supabase console.
325
+
326
+ Shared constants, helper functions, and TypeScript types live under `src/utils/` (`constants/`, `functions/`, `types/`). Some constants serve as placeholders for this demo application.
327
+
328
+ ## ⌨️ Article Manager CLI
329
+
330
+ `scripts/action-script/article-manager.ts` manages articles in Supabase from the command line using the CRUD functions above, run via `tsx` (no TypeScript build config needed):
331
+
332
+ ```bash
333
+ # Insert an article into Supabase
334
+ npx tsx article-manager.ts insert article-slug
335
+
336
+ # Delete an article
337
+ npx tsx article-manager.ts delete article-slug
338
+
339
+ # Update an article
340
+ npx tsx article-manager.ts update article-slug new-article-file
341
+
342
+ # Fetch a single article
343
+ npx tsx article-manager.ts fetch article-slug
344
+
345
+ # Fetch all articles
346
+ npx tsx article-manager.ts fetchAll
347
+ ```
348
+
349
+ The **article slug** is the name of the markdown file in `src/markdown/` minus the `.mdx` extension. The `update` command's second argument follows the same convention.
350
+
351
+ ## πŸ“œ Project Scripts
352
+
353
+ The `/scripts` folder contains tooling for project and database setup:
354
+
355
+ - **`scripts/sql/`** β€” DDL and DML statements for initializing and populating the database
356
+ - **`scripts/powershell/`** β€” Windows setup plus bulk article/S3 helpers (`project_setup.ps1`, `bulk-create-articles.ps1`, `bulk-update-articles.ps1`, `bulk-s3-folder-creation.ps1`, `create-missing-mdx-files.ps1`)
357
+ - **`scripts/bash/`** β€” the same toolkit for Linux/macOS
358
+ - **`scripts/action-script/`** β€” the Article Manager CLI (above)
359
+ - **`scripts/github-gist-fetcher/`** β€” fetches a public gist's raw content to `src/github_gists/<gist-id>.txt`:
360
+ ```bash
361
+ npx tsx scripts/github-gist-fetcher/fetch-github-gist.ts <gist-id>
362
+ ```
363
+ > **Note:** no longer required for rendering β€” `<GitHubGist>` fetches live from the GitHub API. Retained for offline inspection or local caching workflows.
364
+
365
+ ## 🌩️ AWS S3 Image Storage
366
+
367
+ Images referenced in `.mdx` files (via the `MDXImage` component) are served from AWS S3. The allowed external image domain is configured in `next.config.ts` β€” point it at your own bucket, or swap in another storage service entirely.
368
+
369
+ ## πŸ—ΊοΈ SEO: Sitemap, Robots & Structured Data
370
+
371
+ - **`sitemap.xml`** β€” auto-generated at build time by `src/app/sitemap.ts`, covering all static routes and every dynamic article slug fetched from Supabase. Each article's `lastModified` comes from its `updated_at` column (falling back to its publish date)
372
+ - **`robots.txt`** β€” served from `src/app/robots.ts`, permitting all crawlers and pointing them at the sitemap
373
+ - **JSON-LD structured data** β€” every article page embeds a schema.org [`BlogPosting`](https://schema.org/BlogPosting) document (headline, description, cover image, publish/modified dates, author, publisher, tags) for Google rich results. It is rendered server-side by `src/components/ArticleJsonLd.tsx` and built by `src/utils/functions/seo/buildArticleJsonLd.ts`. Validate a deployed page with Google's [Rich Results Test](https://search.google.com/test/rich-results)
374
+
375
+ All of these use `NEXT_PUBLIC_SITE_URL` as the base URL, so set it to your production origin before deploying.
376
+
377
+ ### One-time setup
378
+
379
+ Run **`scripts/sql/DDL/createUpdatedAtTrigger.sql`** once in the Supabase SQL editor. It adds an `updated_at` column to the `Article` table, backfills it from each row's publish date, and keeps it current on every update. Until it is deployed, `dateModified` falls back to the publish date.
380
+
381
+ ## πŸ“± Mobile Responsiveness
382
+
383
+ All components are built mobile-first with Tailwind responsive prefixes (`sm:`, `md:`, `lg:`). Key behaviours:
384
+
385
+ | Component | Mobile behaviour |
386
+ |---|---|
387
+ | `ArticleHeader` | Title scales `text-2xl` β†’ `text-4xl`; author row stacks vertically |
388
+ | `ArticleAuthorBio` | Avatar and text stack vertically; full-width button; center-aligned text |
389
+ | `GitHubGist` | Header wraps via `flex-wrap`; code scrolls horizontally with a styled green scrollbar |
390
+ | `CodeBlock` | Copy button absolutely positioned, never interferes with code flow |
391
+ | `MDXImage` | Container scales inline; hover effect on capable devices |
392
+ | Chat & Code Sandbox | Responsive padding and height calculations across breakpoints |
393
+
394
+ The root layout exports a `viewport` configuration (Next.js `Viewport` type) for correct scaling on all mobile browsers:
395
+
396
+ ```ts
397
+ export const viewport: Viewport = {
398
+ width: 'device-width',
399
+ initialScale: 1,
400
+ };
401
+ ```
402
+
403
+ ## πŸ“Š Analytics
404
+
405
+ Vercel Analytics (`@vercel/analytics`) is integrated to track user interactions and performance metrics β€” kept lightweight and non-blocking.
406
+
407
+ ## 🐳 Docker
408
+
409
+ A multi-stage `Dockerfile` at the project root produces a production image with environment variables injected at runtime:
410
+
411
+ ```bash
412
+ docker build -t mdx-medium-blog .
413
+ ```
414
+
415
+ ```bash
416
+ docker run \
417
+ -e SUPABASE_URL=your_supabase_url \
418
+ -e SUPABASE_ANON_KEY=your_supabase_anon_key \
419
+ -e ANTHROPIC_API_KEY=your_anthropic_api_key \
420
+ -e NEXT_PUBLIC_SITE_URL=https://yourdomain.com \
421
+ -e GITHUB_TOKEN=your_github_token \
422
+ -e GITHUB_USERNAME=your_github_username \
423
+ -e GIST_BASE_URL=https://mdxgists.net \
424
+ -e RESEND_API_KEY=your_resend_api_key \
425
+ -e RESEND_AUDIENCE_ID=your_resend_audience_id \
426
+ -p 3000:3000 mdx-medium-blog
427
+ ```
428
+
429
+ The project also remains compatible with **Vercel** and pure **static hosting** (SSG mode).
430
+
431
+ ## πŸ”— Useful Links
432
+
433
+ - [Next.js Documentation](https://nextjs.org/docs)
434
+ - [MDX Documentation](https://mdxjs.com/docs/)
435
+ - [Lee Robinson's Next.js + MDX Tutorial Video](https://www.youtube.com/watch?v=34bRv6cQezo&ab_channel=leerob)
436
+ - [MDX Playground](https://mdxjs.com/playground/)
437
+ - [React Documentation](https://react.dev/)
438
+ - [Supabase Documentation](https://supabase.com/docs)
439
+ - [Docker Documentation](https://docs.docker.com/)
440
+ - [React Syntax Highlighter](https://github.com/react-syntax-highlighter/react-syntax-highlighter)
441
+ - [Sandpack Documentation](https://sandpack.codesandbox.io/docs)
442
+ - [Pyodide Documentation](https://pyodide.org/en/stable/)
443
+ - [sql.js Documentation](https://sql.js.org/documentation/)
444
+ - [Vercel AI SDK Documentation](https://sdk.vercel.ai/docs)
445
+ - [Anthropic AI SDK Provider](https://sdk.vercel.ai/providers/ai-sdk-providers/anthropic)
446
+ - [Resend Documentation](https://resend.com/docs)
447
+ - [Zod Documentation](https://zod.dev)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-next-mdx-blog-app",
3
- "version": "2.2.7",
3
+ "version": "2.2.9",
4
4
  "description": "A production-ready technical blog starter kit built with Next.js, MDX, Supabase, and TypeScript.",
5
5
  "author": {
6
6
  "name": "Abdullah Muhammad",
@@ -10,7 +10,7 @@
10
10
  "bin/"
11
11
  ],
12
12
  "bin": {
13
- "create-next-mdx-blog-app": "./bin/create.js"
13
+ "create-next-mdx-blog-app": "bin/create.js"
14
14
  },
15
15
  "engines": {
16
16
  "node": ">=18.17.0"
@@ -37,7 +37,7 @@
37
37
  "dev": "next dev",
38
38
  "build": "next build",
39
39
  "start": "next start",
40
- "lint": "next lint",
40
+ "lint": "eslint .",
41
41
  "doctor": "npx react-doctor@latest"
42
42
  },
43
43
  "dependencies": {