### Verify Project Installation Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/installation.md Commands to verify the successful installation and setup of a NextCraft project. These checks include examining the project structure, package.json, type checking, linting, running tests, and building the project. ```bash # Check project structure ls -la # Check package.json cat package.json # Type check pnpm typecheck # Lint pnpm lint # Run tests pnpm test # Build pnpm build ``` -------------------------------- ### NextCraft Development Server Commands Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/installation.md Commands to navigate into the project directory, install dependencies if not already present, and start the development server using Turbopack. Assumes pnpm is the chosen package manager. ```bash cd my-app # If dependencies aren't installed yet pnpm install # Start dev server with Turbopack pnpm dev ``` -------------------------------- ### Build and Start NextCraft with PM2 Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/deployment.md Installs project dependencies, builds the Next.js application, and starts it using PM2. PM2 ensures the application runs reliably in the background. ```bash pnpm install pnpm build pm2 start npm --name "nextcraft-app" -- start pm2 save pm2 startup ``` -------------------------------- ### Create NextCraft App with NPX Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/installation.md Recommended method to create a new NextCraft project using NPX. This command downloads the latest version, runs the interactive CLI, generates the project structure, and installs dependencies. ```bash npx create-nextcraft-app my-app ``` -------------------------------- ### Global Installation of create-nextcraft-app Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/installation.md Installs the NextCraft application generator globally using different package managers (npm, pnpm, yarn, bun). This allows for repeated use of the create-nextcraft-app command without NPX. ```bash # Using npm npm install -g create-nextcraft-app # Using pnpm (faster) pnpm add -g create-nextcraft-app # Using yarn yarn global add create-nextcraft-app # Using bun (fastest) bun add -g create-nextcraft-app ``` -------------------------------- ### Standard Next.js Testing Setup Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/COMPARISON.md Instructions for manually setting up testing in a standard Next.js project, which requires installing Vitest and Testing Library, and configuring their respective files. ```bash # تحتاج تعمل كل ده يدوياً: npm install -D vitest @testing-library/react # Create vitest.config.ts # Create vitest.setup.ts # Configure package.json # Write first test ``` -------------------------------- ### Check Environment Versions Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/installation.md Verify that Node.js, npm/pnpm, and Git are installed and meet the minimum version requirements for NextCraft. These commands are essential for ensuring a compatible development environment. ```bash node --version # Should be v18.17+ npm --version # or pnpm --version git --version ``` -------------------------------- ### Example: Frontend Project with Defaults Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Example command to create a frontend-only NextCraft project using default settings and the '--yes' flag for non-interactive setup. It includes Shadcn UI and enabled SEO. ```bash npx create-nextcraft-app my-frontend-app --yes ``` -------------------------------- ### Netlify Build and Deploy Commands Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/deployment.md Installs the Netlify CLI and deploys the project to Netlify. Assumes the project has build settings configured for Netlify. ```bash pnpm add -g netlify-cli netlify deploy --prod ``` -------------------------------- ### Install Vercel CLI Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/deployment.md Installs the Vercel Command Line Interface globally using pnpm. This tool is essential for deploying Next.js applications to Vercel. ```bash pnpm add -g vercel ``` -------------------------------- ### NextCraft Production Build Command Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/installation.md Command to build the NextCraft project for production deployment. This optimizes the application for performance and size. ```bash pnpm build ``` -------------------------------- ### Standard Next.js UI Setup (Tailwind CSS & Shadcn UI) Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/COMPARISON.md Manual steps to set up Tailwind CSS and Shadcn UI in a standard Next.js project, involving command-line installations and initializations for each component. ```bash # Manual installation npm install tailwindcss npx tailwindcss init # Manual Shadcn setup npx shadcn-ui@latest init npx shadcn-ui@latest add button npx shadcn-ui@latest add card # ... repeat for each component ``` -------------------------------- ### Install Node.js and PM2 for Self-Hosting Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/deployment.md Installs Node.js version 18.x and the PM2 process manager globally on Ubuntu/Debian systems. PM2 is used for managing the Node.js application in production. ```bash curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt-get install -y nodejs sudo npm install -g pm2 ``` -------------------------------- ### Example: Material UI without SEO Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Example command to create a NextCraft project using Material UI and disabling SEO optimization, utilizing the '--yes' flag for a quick setup. ```bash npx create-nextcraft-app simple-app \ --ui material \ --no-seo \ --yes ``` -------------------------------- ### Create NextCraft App Non-Interactively Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/installation.md Utilizes NPX to create a NextCraft project in non-interactive mode, suitable for CI/CD or scripting. Allows specifying project options like mode, UI framework, database, authentication, and defaults. ```bash # With all defaults npx create-nextcraft-app my-app --yes # With specific options npx create-nextcraft-app my-app \ --mode frontend \ --ui shadcn \ --yes # Fullstack with database npx create-nextcraft-app my-fullstack-app \ --mode fullstack \ --ui shadcn \ --db postgres \ --auth \ --yes ``` -------------------------------- ### Example: Fullstack with PostgreSQL & Auth Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Example command to create a fullstack NextCraft project with PostgreSQL database, Auth.js integration, Shadcn UI, and SEO enabled, using the '--yes' flag. ```bash npx create-nextcraft-app my-fullstack-app \ --mode fullstack \ --ui shadcn \ --db postgres \ --auth \ --yes ``` -------------------------------- ### Deploy to Vercel Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/deployment.md Initiates the deployment process for a Next.js project on Vercel. The command guides the user through linking the project and setting up deployment configurations. ```bash vercel ``` -------------------------------- ### Example: RTL-Enabled Project Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Example command to create a NextCraft project with Right-to-Left (RTL) support enabled, suitable for international websites. Configures frontend mode with Shadcn UI. ```bash npx create-nextcraft-app arabic-website \ --mode frontend \ --ui shadcn \ --rtl \ --yes ``` -------------------------------- ### Integrate NextCraft Project Creation into CI/CD Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md This YAML snippet demonstrates a GitHub Actions workflow step for creating a NextCraft project. It uses `npx create-nextcraft-app` with specified options, installs dependencies with `pnpm`, and builds the project. This enables automated project setup in a CI/CD environment. ```yaml # .github/workflows/create-project.yml - name: Create NextCraft project run: | npx create-nextcraft-app test-app \ --mode frontend \ --yes cd test-app pnpm build ``` -------------------------------- ### Configure NextCraft Modules Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/modules.md Example configuration in `nextcraft.config.ts` to specify the project mode and list the enabled modules. Modules listed here will be automatically installed or managed. ```typescript export default defineConfig({ mode: 'fullstack', modules: ['auth', 'users', 'blog'], }); ``` -------------------------------- ### Dockerfile for NextCraft Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/deployment.md A multi-stage Dockerfile to build and run a Next.js application. It optimizes for production by minimizing the final image size and installing only necessary dependencies. ```dockerfile FROM node:18-alpine AS base # Install dependencies only when needed FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app # Install dependencies COPY package.json pnpm-lock.yaml* ./ RUN corepack enable pnpm && pnpm install --frozen-lockfile # Rebuild the source code only when needed FROM base AS builder WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY . . RUN corepack enable pnpm && pnpm build # Production image, copy all the files and run next FROM base AS runner WORKDIR /app ENV NODE_ENV production RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 nextjs COPY --from=builder /app/public ./public COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static USER nextjs EXPOSE 3000 ENV PORT 3000 CMD ["node", "server.js"] ``` -------------------------------- ### Docker Build and Run Commands Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/deployment.md Builds a Docker image for the NextCraft application and runs it as a container. Exposes the application on port 3000. ```bash docker build -t nextcraft-app . docker run -p 3000:3000 nextcraft-app ``` -------------------------------- ### Clear Package Manager Cache Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/installation.md Commands to clear the cache for npm, pnpm, and yarn. This is a troubleshooting step for installation hangs or issues related to corrupted cache data. ```bash # npm npm cache clean --force # pnpm pnpm store prune # yarn yarn cache clean ``` -------------------------------- ### Fix npm Global Permissions Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/installation.md Steps to resolve permission errors when using npm or pnpm globally. This involves configuring npm to install global packages in a user-owned directory and updating the system's PATH. ```bash # Fix npm permissions mkdir ~/.npm-global npm config set prefix '~/.npm-global' echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc source ~/.bashrc ``` -------------------------------- ### Install and Create NextCraft App Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Command to install and create a new NextCraft application. It can be used with a project name and various options for customization. Dependencies include npx. ```bash npx create-nextcraft-app [project-name] [options] ``` -------------------------------- ### Update Node.js using NVM Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/installation.md Instructions for updating Node.js to a required version (v20 LTS recommended) using Node Version Manager (NVM). This is a common solution for 'command not found: npx' errors. ```bash # Using nvm nvm install 20 nvm use 20 ``` -------------------------------- ### NextCraft Testing Commands Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/COMPARISON.md Pre-configured commands in NextCraft for running tests with Vitest, including options for watch mode, coverage reports, and the Vitest UI. ```bash # جاهز من اليوم الأول: pnpm test # Run tests pnpm test:watch # Watch mode pnpm test:coverage # Coverage report pnpm test:ui # Vitest UI ``` -------------------------------- ### NextCraft Dependencies (package.json) Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/COMPARISON.md The comprehensive list of dependencies included in a NextCraft setup, featuring advanced tools for state management, form handling, validation, UI, testing, and development. ```json { "dependencies": { "next": "^16.0.1", "react": "^19.2.0", "react-dom": "^19.2.0", "@tanstack/react-query": "^5.60.0", "zustand": "^5.0.3", "react-hook-form": "^7.54.0", "zod": "^3.24.1", "framer-motion": "^11.15.0" // + 15 more production-ready packages }, "devDependencies": { "typescript": "^5.7.0", "eslint": "^9.16.0", "prettier": "^3.4.2", "husky": "^9.1.7", "vitest": "^2.1.8", "@testing-library/react": "^16.1.0" // + 12 more quality tools } } ``` -------------------------------- ### Detect Package Manager and Commands (TypeScript) Source: https://context7.com/ziadmustafa1/nextcraft/llms.txt This snippet shows how to automatically detect the package manager (pnpm, npm, yarn, bun) used in a project. It utilizes utility functions to get the appropriate installation, development, and package addition commands based on the detected manager. This ensures consistency in project setup and dependency management. ```typescript import { detectPackageManager, getInstallCommand, getDevCommand, getAddCommand } from './utils/package-manager'; // Auto-detect package manager from environment const pm = detectPackageManager(); // Returns: 'pnpm' | 'npm' | 'yarn' | 'bun' // Detection order: npm_config_user_agent → available commands → npm fallback console.log(pm); // 'pnpm' console.log(getInstallCommand(pm)); // 'pnpm install' console.log(getDevCommand(pm)); // 'pnpm dev' // Generate add command for multiple packages const addCmd = getAddCommand(pm, ['axios', 'zod', 'react-hook-form']); console.log(addCmd); // 'pnpm add axios zod react-hook-form' ``` -------------------------------- ### Barrel Exports Example Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/project-structure.md Demonstrates the use of barrel exports with an `index.ts` file to simplify imports from a module or component directory. ```typescript // components/ui/index.ts export { Button } from './button' export { Card } from './card' // Usage import { Button, Card } from '@/components/ui' ``` -------------------------------- ### Use Inline Server Actions in Example Components Source: https://github.com/ziadmustafa1/nextcraft/blob/master/FIXES_APPLIED.md This code illustrates how example components like `OptimisticList` and `LoginForm` now define their server actions inline using `'use server'`. This approach avoids external imports for actions and keeps the examples self-contained, improving clarity and demonstrating direct server action usage within components. ```typescript // Mock add item action for demo purposes async function addItem(name: string): Promise<{ id: string; name: string }> { 'use server' await new Promise(resolve => setTimeout(resolve, 1000)) return { id: Math.random().toString(36).slice(2), name } } // Mock login action for demo purposes async function loginUser( _prevState: { error: string | null; success: boolean }, formData: FormData ): Promise<{ error: string | null; success: boolean }> { 'use server' // ... validation logic inline } ``` -------------------------------- ### Default NextCraft Configuration Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/configuration.md Sets up a fullstack NextCraft project with Shadcn UI, PostgreSQL, authentication, and user/auth modules. This is a common starting point for feature-rich applications. ```typescript import { defineConfig } from '@nextcraft/core'; export default defineConfig({ mode: 'fullstack', ui: 'shadcn', db: 'postgres', auth: true, rtl: false, seo: true, modules: ['auth', 'users'], }); ``` -------------------------------- ### Install a NextCraft Module Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/modules.md Command to add a specific module to your NextCraft project. Replace with the desired module (e.g., auth, users). ```bash forge add ``` -------------------------------- ### Run Database Migrations Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/deployment.md Deploys database migrations using Prisma. This command ensures the database schema is up-to-date with the application's requirements. It can be run during the build process on platforms like Vercel/Netlify or manually. ```bash # On Vercel/Netlify, use build command: pnpm prisma migrate deploy && pnpm build # Or manually: pnpm prisma migrate deploy ``` -------------------------------- ### Install Blog Module Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/modules.md Command to add the blogging system module to your NextCraft project. It includes Markdown support, post management, categories, tags, and RSS feed generation. ```bash forge add blog ``` -------------------------------- ### Standard Next.js Dependencies (package.json) Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/COMPARISON.md The default dependencies for a standard Next.js project, typically including Next.js, React, and basic development tools like TypeScript and ESLint. ```json { "dependencies": { "next": "14.x", "react": "^18", "react-dom": "^18" }, "devDependencies": { "typescript": "^5", "eslint": "^8", "eslint-config-next": "14.x" } } ``` -------------------------------- ### Type Safety Example Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/project-structure.md Illustrates implementing type safety in a React component using TypeScript interfaces for props and defining function signatures. ```typescript interface Props { user: User onUpdate: (user: User) => void } export function UserCard({ user, onUpdate }: Props) { // ... } ``` -------------------------------- ### Display NextCraft Version Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Displays the installed version number of the create-nextcraft-app CLI tool. ```bash create-nextcraft-app --version ``` -------------------------------- ### Configure NextCraft App Mode Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Specifies the project mode for a NextCraft application. Available modes are 'frontend' for UI and server actions, and 'fullstack' for a complete setup including database and API. ```bash npx create-nextcraft-app my-app --mode frontend npx create-nextcraft-app my-app --mode fullstack ``` -------------------------------- ### NextCraft Environment Variables (.env) Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Example of environment variables typically configured in a '.env' file for a NextCraft project, especially for fullstack applications. Includes settings for database connection and Auth.js. ```env # Database DATABASE_URL="postgresql://user:password@localhost:5432/mydb" # Auth.js (if --auth enabled) NEXTAUTH_URL="http://localhost:3000" NEXTAUTH_SECRET="run: openssl rand -base64 32" # OAuth Providers (optional) GITHUB_ID="your-github-client-id" GITHUB_SECRET="your-github-client-secret" ``` -------------------------------- ### Remove Async Page Example Due to Cache Compatibility Source: https://github.com/ziadmustafa1/nextcraft/blob/master/FIXES_APPLIED.md This code snippet shows the removal of an async page example from `next16-setup.ts`. The explanation clarifies that the `export const dynamic = 'force-dynamic'` setting in the async page conflicts with the new `cacheComponents: true` configuration in Next.js 16, making the example incompatible. ```typescript // ❌ قبل const examplesDir = path.join(this.projectPath, 'src', 'app', '(examples)', 'async-page'); await ensureDir(examplesDir); await writeFile(path.join(examplesDir, 'page.tsx'), asyncPageTemplate); // ✅ بعد // Note: Async page example removed due to cacheComponents compatibility // The async-page example conflicts with cacheComponents setting // Users can create their own async pages as needed ``` -------------------------------- ### Dynamic Configuration with Environment Variables Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/configuration.md Demonstrates how to dynamically configure NextCraft settings using environment variables. This allows for flexible project setup based on the runtime environment, such as development or production. ```typescript export default defineConfig({ mode: process.env.NODE_ENV === 'production' ? 'fullstack' : 'frontend', ui: 'shadcn', db: process.env.DATABASE_URL ? 'postgres' : 'sqlite', auth: true, seo: true, }); ``` -------------------------------- ### Environment Variables for Fullstack Projects Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/configuration.md Example of essential environment variables for a fullstack NextCraft project, including database connection strings and authentication secrets. These variables are crucial for connecting to databases and securing authentication. ```bash # Database DATABASE_URL="postgresql://user:password@localhost:5432/mydb" # Authentication (if auth: true) NEXTAUTH_URL="http://localhost:3000" NEXTAUTH_SECRET="your-secret-key-change-in-production" # Optional NODE_ENV="development" ``` -------------------------------- ### Install Payments Module Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/modules.md Command to add the payment integration module to your NextCraft project. It supports Stripe integration, checkout flows, and webhook handling. ```bash forge add payments ``` -------------------------------- ### Environment Variables (.env) Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/project-structure.md Example environment variables for a fullstack Next.js application, including database connection, authentication secrets, OAuth provider keys, and API URLs. Differentiates between server-only and browser-exposed variables. ```env # Database DATABASE_URL="postgresql://user:password@localhost:5432/mydb" # Auth.js NEXTAUTH_URL="http://localhost:3000" NEXTAUTH_SECRET="your-secret-key-here" # OAuth Providers (optional) GITHUB_ID="your-github-client-id" GITHUB_SECRET="your-github-client-secret" # API Keys NEXT_PUBLIC_API_URL="https://api.example.com" ``` -------------------------------- ### Enable Authentication in NextCraft Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Enables authentication using Auth.js in a NextCraft project. This option simplifies the setup of user authentication flows. ```bash npx create-nextcraft-app my-app --auth ``` -------------------------------- ### Install Auth Module Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/modules.md Command to add the built-in authentication module to your NextCraft project. This module provides features like credentials authentication, JWT sessions, and user management. ```bash forge add auth ``` -------------------------------- ### Install Users Module Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/modules.md Command to add the user management module to your NextCraft project. This module enables User CRUD operations, user lists, and profile management. ```bash forge add users ``` -------------------------------- ### Install Admin Module Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/modules.md Command to add the admin dashboard module to your NextCraft project. This module provides a layout for administration, stats widgets, user management, and settings. ```bash forge add admin ``` -------------------------------- ### Optimistic UI with useOptimistic in React Source: https://github.com/ziadmustafa1/nextcraft/blob/master/apps/website/NEXTJS_16.md Provides an example of implementing Optimistic UI using the `useOptimistic` hook from React. This allows the UI to update immediately with the anticipated result of an action before the server confirms it, enhancing the perceived performance and user experience. The example shows updating a todo list optimistically. ```typescript 'use client' import { useOptimistic } from 'react' export function TodoList({ todos }) { const [optimisticTodos, addOptimistic] = useOptimistic( todos, (state, newTodo) => [...state, newTodo] ) return (
{ const todo = formData.get('todo') addOptimistic({ text: todo }) await createTodo(todo) }}> {optimisticTodos.map(todo =>
{todo.text}
)}
) } ``` -------------------------------- ### NextCraft Interactive Mode Prompts Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Illustrates the interactive prompts displayed by the create-nextcraft-app command when the '--yes' flag is not used. Users are guided through project name, mode, UI, database, auth, and RTL settings. ```text 🎨 Welcome to NextCraft ? What is your project name? › my-app ? Select project mode › ❯ Frontend (UI + Server Actions) Fullstack (Frontend + Database + API) ? Select UI framework › ❯ Shadcn UI (Recommended) Chakra UI Material UI ? Select database (fullstack only) › ❯ PostgreSQL SQLite (for development) MySQL ? Enable authentication? › No / Yes ? Enable RTL support? › No / Yes ? Enable SEO optimization? › Yes / No ``` -------------------------------- ### Install Dashboard Module Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/modules.md Command to add the analytics dashboard module to your NextCraft project. Features include charts, analytics widgets, and real-time data display. ```bash forge add dashboard ``` -------------------------------- ### Force Install a Module with Conflicts Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/modules.md Command to forcefully add a module, overwriting any conflicting files in your project. Use this option with caution as it can lead to data loss or unexpected behavior. ```bash forge add --force ``` -------------------------------- ### Configuration Constants and Defaults in TypeScript Source: https://context7.com/ziadmustafa1/nextcraft/llms.txt Illustrates the usage of various configuration constants and defaults imported from './constants'. This includes the NextCraft version, default project configuration, available modules, UI frameworks, and database providers. The examples show how to log these values. ```typescript import { NEXTCRAFT_VERSION, DEFAULT_CONFIG, AVAILABLE_MODULES, UI_FRAMEWORKS, DATABASE_PROVIDERS } from './constants'; console.log(NEXTCRAFT_VERSION); // '0.1.0' console.log(DEFAULT_CONFIG); // { // mode: 'frontend', // ui: 'shadcn', // auth: false, // rtl: false, // seo: true, // modules: [] // } console.log(AVAILABLE_MODULES); // ['auth', 'users', 'blog', 'admin', 'dashboard', 'payments'] console.log(UI_FRAMEWORKS.shadcn); // { // name: 'Shadcn UI', // description: 'Beautifully designed components...', // dependencies: ['@radix-ui/react-slot', 'class-variance-authority', ...] // } console.log(DATABASE_PROVIDERS.postgres); // { // name: 'PostgreSQL', // url: 'postgresql://user:password@localhost:5432/dbname' // } ``` -------------------------------- ### Standard Next.js TypeScript Configuration (tsconfig.json) Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/COMPARISON.md A basic TypeScript configuration for a standard Next.js project, where strict mode is disabled, allowing for more flexibility but potentially leading to runtime errors. ```typescript // tsconfig.json { "strict": false // ❌ أي نوع allowed } // Example function getUser(id: any): any { return fetch(`/api/${id}`) } ``` -------------------------------- ### TailwindCSS 4 Setup and CSS Syntax Update Source: https://github.com/ziadmustafa1/nextcraft/blob/master/BUILD_SUCCESS.md Configures PostCSS for TailwindCSS version 4 and updates the global CSS syntax. It replaces the deprecated 'tailwindcss' plugin with '@tailwindcss/postcss' and adapts CSS rules to the new v4 syntax, including using `@theme` for variables. ```javascript // ❌ Old postcss.config.js plugins: { tailwindcss: {}, autoprefixer: {}, } // ✅ New postcss.config.js plugins: { '@tailwindcss/postcss': {}, } ``` ```css /* ❌ Old globals.css */ @tailwind base; @tailwind components; @tailwind utilities; @layer base { @apply border-border; /* Not compatible with v4 */ } /* ✅ New globals.css (v4 syntax) */ @import "tailwindcss"; * { border-color: hsl(var(--border)); } @theme { --color-background: 0 0% 100%; --color-foreground: 222.2 84% 4.9%; /* ... */ } ``` -------------------------------- ### Fix npm Global Permissions Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md This command sequence resolves 'Permission denied' errors when using npm by setting up a global npm directory and configuring npm to use it. This ensures that npm packages can be installed globally without requiring `sudo`. ```bash # Fix permissions mkdir ~/.npm-global npm config set prefix '~/.npm-global' ``` -------------------------------- ### NextCraft TypeScript Configuration (tsconfig.json) Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/COMPARISON.md The strict TypeScript configuration in NextCraft, enforcing type safety by enabling various strictness options and demonstrating type-safe data fetching with Zod validation. ```typescript // tsconfig.json { "strict": true, "noImplicitAny": true, "strictNullChecks": true, "noUnusedLocals": true, "noUncheckedIndexedAccess": true } // Example const UserSchema = z.object({ id: z.string(), name: z.string(), }) type User = z.infer async function getUser(id: string): Promise { const response = await fetch(`/api/users/${id}`) return UserSchema.parse(await response.json()) } ``` -------------------------------- ### Frontend Project with RTL Support Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/configuration.md Configures a frontend-only NextCraft project with Shadcn UI and enabled RTL support for multi-language compatibility. This setup is ideal for applications targeting audiences that use right-to-left scripts. ```typescript export default defineConfig({ mode: 'frontend', ui: 'shadcn', rtl: true, seo: true, }); ``` -------------------------------- ### API Client Setup with Axios (TypeScript) Source: https://context7.com/ziadmustafa1/nextcraft/llms.txt Sets up an auto-generated Axios client for making API requests. It includes request interceptors for adding authorization tokens and response interceptors for handling 401 errors, redirecting to login. Dependencies include axios. ```typescript // src/lib/api-client.ts - Auto-generated Axios client import axios, { AxiosInstance } from 'axios'; class APIClient { private client: AxiosInstance; constructor(baseURL: string = process.env.NEXT_PUBLIC_API_URL || '') { this.client = axios.create({ baseURL, timeout: 10000, headers: { 'Content-Type': 'application/json' } }); this.setupInterceptors(); } private setupInterceptors(): void { // Request interceptor adds auth token this.client.interceptors.request.use((config) => { const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null; if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); // Response interceptor handles 401 this.client.interceptors.response.use( (response) => response, (error) => { if (error.response?.status === 401) { if (typeof window !== 'undefined') { localStorage.removeItem('token'); window.location.href = '/login'; } } return Promise.reject(error); } ); } async get(url: string, config?: any): Promise { const response = await this.client.get(url, config); return response.data; } async post(url: string, data?: any, config?: any): Promise { const response = await this.client.post(url, data, config); return response.data; } } export const api = new APIClient(); // Usage: // const user = await api.get('/api/users/me'); // const result = await api.post('/api/data', { foo: 'bar' }); ``` -------------------------------- ### Create Next.js App Non-Interactively (Bash) Source: https://context7.com/ziadmustafa1/nextcraft/llms.txt Creates a new Next.js project with NextCraft using default settings or specified flags for a quick, automated setup. This is ideal for CI/CD pipelines or rapid project initialization. ```bash # Quick setup with defaults (frontend + shadcn + SEO) npx create-nextcraft-app my-app --yes # Fullstack project with all options npx create-nextcraft-app my-fullstack-app \ --mode fullstack \ --ui shadcn \ --db postgres \ --auth \ --rtl \ --yes # Frontend with Material UI and RTL support npx create-nextcraft-app arabic-app \ --mode frontend \ --ui material \ --rtl \ --yes ``` -------------------------------- ### Verify Node.js Version Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md This command helps troubleshoot 'Command not found' errors by verifying the installed Node.js version. It requires Node.js v18.17 or higher for NextCraft projects. This is a crucial step for ensuring the development environment is correctly set up. ```bash node --version # Should be v18.17+ ``` -------------------------------- ### Async Page Rendering in Next.js 16 Source: https://github.com/ziadmustafa1/nextcraft/blob/master/apps/website/NEXTJS_16.md Illustrates the asynchronous page rendering capabilities in Next.js 16. This example shows how a page component can directly `await` promises for route parameters and search parameters, enabling more dynamic and performant page loads by fetching data concurrently. ```typescript export default async function Page({ params, searchParams }: { params: Promise<{ id: string }> searchParams: Promise<{ q: string }> }) { const { id } = await params const { q } = await searchParams return
ID: {id}, Query: {q}
} ``` -------------------------------- ### Next.js 16 Optimized Configuration (TypeScript) Source: https://context7.com/ziadmustafa1/nextcraft/llms.txt Provides an example of an optimized `next.config.ts` file for Next.js 16. It includes settings for React strict mode, Partial Prerendering (PPR), image optimization formats, and TypeScript build error handling. It also defines security headers for enhanced application protection. ```typescript // next.config.ts - Generated with optimizations import type { NextConfig } from 'next'; const nextConfig: NextConfig = { reactStrictMode: true, // Next.js 16 - Partial Prerendering (PPR) cacheComponents: true, // Image optimization images: { formats: ['image/avif', 'image/webp'], remotePatterns: [] }, // TypeScript build-time checking typescript: { ignoreBuildErrors: false }, // Security headers async headers() { return [{ source: '/:path*', headers: [ { key: 'X-DNS-Prefetch-Control', value: 'on' }, { key: 'X-Frame-Options', value: 'SAMEORIGIN' }, { key: 'X-Content-Type-Options', value: 'nosniff' } ] }]; } }; export default nextConfig; ``` -------------------------------- ### Display NextCraft Help Information Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Shows comprehensive help information for the create-nextcraft-app command, detailing all available options and their usage. ```bash create-nextcraft-app --help ``` -------------------------------- ### Create NextCraft App - Basic Usage Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Demonstrates basic usage of the create-nextcraft-app command for initializing a new project. Supports interactive mode, specifying a project name, and non-interactive mode with the --yes flag. ```bash # Interactive mode (default) npx create-nextcraft-app my-app # With project name npx create-nextcraft-app my-awesome-project # Non-interactive with defaults npx create-nextcraft-app my-app --yes ``` -------------------------------- ### ESLint Configuration (Flat Config) Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/project-structure.md Sets up ESLint using the flat configuration format for version 9, including recommended rules and specific overrides for TypeScript and console usage. ```javascript export default [ js.configs.recommended, ...compat.extends('next/core-web-vitals', 'next/typescript'), { rules: { '@typescript-eslint/no-explicit-any': 'error', '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^ _', }], 'no-console': ['warn', { allow: ['warn', 'error'] }], }, }, ] ``` -------------------------------- ### Configure Default NextCraft Options Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md This snippet shows how to create a default configuration file (`~/.nextcraftrc`) for NextCraft. It specifies project mode, UI framework, and SEO settings. This file is essential for setting up new projects with consistent options. ```json { "mode": "frontend", "ui": "shadcn", "seo": true } ``` -------------------------------- ### Configure NextCraft Database (Fullstack) Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Selects the database for a fullstack NextCraft project. Options include 'postgres', 'sqlite', and 'mysql'. This is only applicable when the --mode is set to 'fullstack'. ```bash npx create-nextcraft-app my-app --mode fullstack --db postgres npx create-nextcraft-app my-app --mode fullstack --db sqlite ``` -------------------------------- ### Generate NextAuth Secret Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/deployment.md Generates a secure, random base64 encoded secret for NextAuth.js using OpenSSL. This secret is crucial for session management and should be kept confidential. ```bash openssl rand -base64 32 ``` -------------------------------- ### Configure NextCraft UI Framework Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md Selects the UI framework for a NextCraft project. Supported frameworks include 'shadcn', 'chakra', and 'material'. This option customizes the frontend components. ```bash npx create-nextcraft-app my-app --ui shadcn npx create-nextcraft-app my-app --ui chakra npx create-nextcraft-app my-app --ui material ``` -------------------------------- ### Package Scripts for Nextcraft Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/project-structure.md Defines various npm scripts for managing the Nextcraft project, including development, building, linting, formatting, testing, and validation tasks. ```json { "scripts": { "dev": "next dev --turbo", "build": "next build", "start": "next start", "lint": "eslint . --ext .ts,.tsx --max-warnings 0", "lint:fix": "eslint . --ext .ts,.tsx --fix", "format": "prettier --write \"**/*.{ts,tsx,json,md}\"", "format:check": "prettier --check \"**/*.{ts,tsx,json,md}\"", "typecheck": "tsc --noEmit", "test": "vitest run", "test:watch": "vitest", "test:coverage": "vitest run --coverage", "test:ui": "vitest --ui", "validate": "pnpm lint && pnpm typecheck && pnpm test" } } ``` -------------------------------- ### Fullstack Project with Auth and Admin Modules Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/configuration.md Sets up a fullstack NextCraft project with PostgreSQL, authentication, and includes 'auth', 'users', and 'admin' modules. This configuration is for comprehensive applications requiring backend, auth, and administrative functionalities. ```typescript export default defineConfig({ mode: 'fullstack', ui: 'shadcn', db: 'postgres', auth: true, seo: true, modules: ['auth', 'users', 'admin'], }); ``` -------------------------------- ### Nginx Configuration for Reverse Proxy Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/deployment.md Configures Nginx as a reverse proxy to forward requests from port 80 to the Next.js application running on port 3000. This is typically used for self-hosted deployments. ```nginx server { listen 80; server_name yourdomain.com; location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } ``` -------------------------------- ### Tailwind CSS Configuration Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/project-structure.md Configures Tailwind CSS for the project, specifying content paths and integrating the tailwindcss-animate plugin. ```javascript module.exports = { content: [ './src/**/*.{ts,tsx,js,jsx}', ], theme: { extend: {}, }, plugins: [require('tailwindcss-animate')], } ``` -------------------------------- ### Interactive Project Configuration in TypeScript Source: https://context7.com/ziadmustafa1/nextcraft/llms.txt Demonstrates how to use prompts to gather user input for project configuration, including mode, UI framework, database, authentication, RTL support, and SEO. It also shows how to confirm directory overwrites. Dependencies include './prompts'. ```typescript import { promptForProjectOptions, confirmOverwrite } from './prompts'; // Interactive project configuration const options = await promptForProjectOptions('my-app'); // User is prompted for: // - Project mode (frontend/fullstack) // - UI framework (shadcn/chakra/material) // - Database (postgres/sqlite/mysql) - if fullstack // - Authentication (yes/no) // - RTL support (yes/no) // - SEO optimization (yes/no) console.log(options); // { // name: 'my-app', // mode: 'fullstack', // ui: 'shadcn', // database: 'postgres', // auth: true, // rtl: false, // seo: true // } // Confirm overwrite if directory exists const shouldOverwrite = await confirmOverwrite('/path/to/project'); if (!shouldOverwrite) { console.log('Operation cancelled'); process.exit(0); } ``` -------------------------------- ### Next.js Core Configuration (next.config.ts) Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/project-structure.md Configuration file for Next.js applications, enabling features like React Strict Mode and PPR (Partial Prerendering). It also specifies image formats and allows for security header configurations. ```typescript const nextConfig: NextConfig = { reactStrictMode: true, cacheComponents: true, // PPR enabled images: { formats: ['image/avif', 'image/webp'] }, // ... security headers } ``` -------------------------------- ### Lint-Staged Configuration Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/project-structure.md Configures lint-staged to automatically lint and format staged TypeScript and TSX files using ESLint and Prettier. ```json { "*.{ts,tsx}": [ "eslint --fix", "prettier --write" ] } ``` -------------------------------- ### Prettier Configuration Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/getting-started/project-structure.md Defines code formatting rules for Prettier, including semicolon usage, quote style, tab width, print width, and the inclusion of the Prettier Tailwind CSS plugin. ```json { "semi": false, "singleQuote": true, "tabWidth": 2, "printWidth": 100, "plugins": ["prettier-plugin-tailwindcss"] } ``` -------------------------------- ### SWR to TanStack Query Migration Source: https://github.com/ziadmustafa1/nextcraft/blob/master/BUILD_SUCCESS.md Migrates data fetching logic from SWR to TanStack Query, which is presented as the industry standard. The `useFetch` hook is refactored to use `useQuery` from `@tanstack/react-query`, updating the query key and query function structure. ```typescript // ❌ Old (SWR) import useSWR from 'swr' export function useFetch(url, config) { return useSWR(url, fetcher, config) } // ✅ New (TanStack Query - Industry Standard) import { useQuery } from '@tanstack/react-query' export function useFetch(url: string, options) { return useQuery({ queryKey: [url], queryFn: () => api.get(url), ...options, }) } ``` -------------------------------- ### Package.json Dependencies Source: https://github.com/ziadmustafa1/nextcraft/blob/master/BUILD_SUCCESS.md Lists the production and development dependencies for the project, including versions for Next.js, React, TanStack Query, TailwindCSS, and other essential libraries. ```json { "dependencies": { "next": "^16.0.1", "react": "^19.2.0", "react-dom": "^19.2.0", "@tanstack/react-query": "^5.60.0", "zustand": "^5.0.3", "react-hook-form": "^7.54.0", "zod": "^3.24.1", "framer-motion": "^11.15.0", "// ... 17 total" }, "devDependencies": { "tailwindcss": "^4.1.0", "@tailwindcss/postcss": "^4.1.0", "eslint": "^9.16.0", "prettier": "^3.4.2", "husky": "^9.1.7", "vitest": "^2.1.8", "// ... 20 total" } } ``` -------------------------------- ### Replace SWR with TanStack Query for use-fetch Hook Source: https://github.com/ziadmustafa1/nextcraft/blob/master/FIXES_APPLIED.md This code demonstrates the migration of a `useFetch` hook from SWR to TanStack Query (`@tanstack/react-query`). It shows the change in import statements and the structure of the hook implementation, adopting TanStack Query's `useQuery` hook for data fetching. ```typescript // ❌ قبل (SWR) import useSWR from 'swr' export function useFetch(url: string, config?: SWRConfiguration) { return useSWR(url, fetcher, config) } // ✅ بعد (TanStack Query - Industry Standard) import { useQuery, UseQueryOptions } from '@tanstack/react-query' export function useFetch( url: string, options?: Omit, 'queryKey' | 'queryFn'> ) { return useQuery({ queryKey: [url], queryFn: () => api.get(url), ...options, }) } ``` -------------------------------- ### TanStack Query Hook for Data Fetching (TypeScript) Source: https://context7.com/ziadmustafa1/nextcraft/llms.txt Provides a custom hook `useFetch` using TanStack Query for efficient data fetching. It integrates with the `api-client` for making GET requests and accepts standard `useQuery` options. Dependencies include `@tanstack/react-query` and the local `api-client`. ```typescript // src/hooks/use-fetch.ts - Industry-standard data fetching import { useQuery, UseQueryOptions } from '@tanstack/react-query'; import { api } from '@/lib/api-client'; export function useFetch( url: string, options?: Omit, 'queryKey' | 'queryFn'> ) { return useQuery({ queryKey: [url], queryFn: () => api.get(url), ...options, }); } // Usage in React component: import { useFetch } from '@/hooks/use-fetch'; interface User { id: string; name: string; email: string; } function UserProfile() { const { data, isLoading, error } = useFetch('/api/users/me', { retry: 3, staleTime: 5000 }); if (isLoading) return
Loading...
; if (error) return
Error: {error.message}
; return (

{data?.name}

{data?.email}

); } ``` -------------------------------- ### NextCraft Project Configuration File (TypeScript) Source: https://context7.com/ziadmustafa1/nextcraft/llms.txt Defines the structure for the `nextcraft.config.ts` file, which holds project-specific settings. This configuration object specifies project mode, UI framework, database, authentication, and other features. It's used by tools like `forge doctor` for validation and `forge add` for module installation. ```typescript // nextcraft.config.ts - Auto-generated in project root import { NextCraftConfig } from '@nextcraft/types'; const config: NextCraftConfig = { mode: 'fullstack', ui: 'shadcn', db: 'postgres', auth: true, rtl: false, seo: true, modules: ['auth', 'users'] }; export default config; // Configuration is used by: // - forge doctor (validation) // - forge add (module installation) // - Project structure validation ``` -------------------------------- ### Configure npm Registry Source: https://github.com/ziadmustafa1/nextcraft/blob/master/docs/api/cli-commands.md This command allows users to troubleshoot 'Network timeout' errors by explicitly setting the npm registry URL. It ensures that npm attempts to download packages from the official npm registry, which can resolve connectivity issues. ```bash npm config set registry https://registry.npmjs.org/ ``` -------------------------------- ### Generate Fullstack Project with Database (TypeScript) Source: https://context7.com/ziadmustafa1/nextcraft/llms.txt Demonstrates creating a fullstack Next.js project using the FullstackGenerator class. It initializes the generator with project options like UI framework, database, and authentication, then calls the generate method. The generated project includes backend API routes, database schema, and environment configuration. ```typescript import { FullstackGenerator } from './generators/fullstack-generator'; import { ProjectOptions } from './types'; // Create a fullstack project with database const options: ProjectOptions = { name: 'my-fullstack-app', mode: 'fullstack', ui: 'shadcn', database: 'postgres', auth: true, rtl: false, seo: true, path: '/path/to/project' }; const generator = new FullstackGenerator(options); await generator.generate(); // Generated fullstack project includes everything from frontend plus: // - prisma/schema.prisma with User model // - src/lib/db/prisma.ts with connection pooling // - src/app/api/auth/[...nextauth]/route.ts // - src/app/api/health/route.ts // - .env.example with DATABASE_URL and NEXTAUTH_SECRET // - Database migrations ready to run ```