### Quick Start Commands for Next.js App Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/apps/nextjs-app/README.md These commands outline the initial setup and development process for the Next.js application within the monorepo. It involves installing dependencies, navigating to the app directory, and starting the development server. ```bash $ yarn install $ cd apps/nextjs-app $ yarn dev ``` -------------------------------- ### Install Docker and Dependencies on Ubuntu Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docs/docker/docker.md Commands to install Docker Engine, CLI, containerd, buildx plugin, and Compose plugin on Ubuntu systems. It includes steps to remove existing Docker installations and configure the official Docker repository. ```bash sudo apt-get remove docker docker-engine docker.io containerd runc curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg echo \ "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin ``` -------------------------------- ### Enable Corepack and Install Dependencies (Bash) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/TROUBLESHOOT.md This snippet shows how to enable the experimental corepack utility to manage package managers and then install project dependencies using yarn. This is a prerequisite for project setup if corepack is not already enabled. ```bash corepack enable yarn install ``` -------------------------------- ### Launch Next.js Server Locally Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/apps/nextjs-app/e2e/README.md This snippet provides commands to build and start a Next.js application, or to run it in development mode directly from the command line. ```bash cd apps/nextjs-app yarn build && yarn start # or yarn dev ``` -------------------------------- ### Complete Docker Removal Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docs/docker/docker.md Commands for a complete removal of Docker, including its data directory. This action is destructive and will result in data loss. Use with extreme caution. ```bash systemctl docker stop rm -rd /var/lib/docker systemctl docker start ``` -------------------------------- ### Build Next.js App (Builder Stage) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docs/docker/docker.md Commands to build the Next.js application in the 'builder' stage. This stage typically involves installing dependencies, building the application, and removing development dependencies. Requires specific build arguments (environment variables) for a production build. ```bash DOCKER_BUILDKIT=1 docker-compose -f docker-compose.nextjs-app.yml build --progress=tty builder ``` ```bash DOCKER_BUILDKIT=1 docker-compose -f docker-compose.nextjs-app.yml build --no-cache --force-rm --progress=tty builder ``` ```bash DOCKER_BUILDKIT=1 docker-compose -f docker-compose.nextjs-app.yml run --rm builder sh ``` -------------------------------- ### Docker Compose for Database Initialization Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/apps/nextjs-app/README.md This command is used to start the necessary database services defined in the docker-compose file. This is a prerequisite for accessing the rest/api database. ```bash docker-compose up main-db ``` -------------------------------- ### Build and Run Next.js Monorepo with Docker Compose Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docker/README.md Commands to build the Docker images for the Next.js monorepo and start the application using Docker Compose. Includes options for verbose builds and parallel execution. After building, 'docker compose up' starts the services, and 'docker compose down' stops them. ```bash cd ./docker docker compose build docker compose build --progress=plain # More verbose docker compose build --parallel # Might be faster docker compose up docker compose down ``` -------------------------------- ### Install Dependencies with Yarn Workspaces Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Demonstrates installing dependencies in a monorepo using Yarn. It covers enabling Corepack for Yarn 4 support, installing all workspace dependencies, adding packages to specific workspaces, and using the workspace protocol for shared package dependencies. ```bash # Enable Corepack for Yarn 4 support corepack enable # Install all workspace dependencies yarn install # Add a package to a specific workspace cd apps/nextjs-app yarn add lodash # Add a shared package as dependency using workspace protocol yarn add @your-org/core-lib@'workspace:^' ``` -------------------------------- ### Docker Cleanup Commands Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docs/docker/docker.md A table outlining various Docker cleanup commands to manage build artifacts, images, containers, and volumes. Use these commands to free up disk space and maintain a clean Docker environment. ```bash docker buildx prune ``` ```bash docker builder prune --filter type=exec.cachemount ``` ```bash docker container rm -f $(docker container ls -qa) ``` ```bash docker image rm -f $(docker image ls -q) ``` ```bash docker volume rm $(docker volume ls -q) ``` -------------------------------- ### Build Docker Image Dependencies Stage Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docs/docker/docker.md Commands to build the 'deps' stage of the Docker image independently. This stage is responsible for installing monorepo dependencies and making node_modules available to subsequent stages. ```bash DOCKER_BUILDKIT=1 docker-compose -f docker-compose.nextjs-app.yml build --progress=tty deps # docker buildx bake -f docker-compose.nextjs-app.yml --progress=tty deps ``` -------------------------------- ### Run Next.js App (Runner Stage) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docs/docker/docker.md Commands to run the production build of the Next.js application in the 'runner' stage. The application will listen on http://localhost:3000 by default. Requires a .env file with necessary runtime variables. ```bash DOCKER_BUILDKIT=1 docker-compose -f docker-compose.nextjs-app.yml --env-file .env.secret up runner ``` ```bash DOCKER_BUILDKIT=1 docker-compose -f docker-compose.nextjs-app.yml build --progress=tty runner ``` ```bash DOCKER_BUILDKIT=1 docker-compose -f docker-compose.nextjs-app.yml build --no-cache --force-rm --progress=tty runner ``` ```bash DOCKER_BUILDKIT=1 docker-compose -f docker-compose.nextjs-app.yml run --rm runner sh ``` -------------------------------- ### Open Shell in Docker Dependencies Stage Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docs/docker/docker.md Command to open a shell within the Docker 'deps' stage. This allows inspection and debugging of the environment where monorepo dependencies are installed. ```bash DOCKER_BUILDKIT=1 docker-compose -f docker-compose.nextjs-app.yml run --rm deps sh ``` -------------------------------- ### Force Rebuild Docker Image Dependencies Stage Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docs/docker/docker.md Command to force a rebuild of the 'deps' stage of the Docker image, ignoring any cached layers. This is useful when dependency changes need to be fully reapplied. ```bash DOCKER_BUILDKIT=1 docker-compose -f docker-compose.nextjs-app.yml build --no-cache --force-rm --progress=tty deps ``` -------------------------------- ### Open Shell in Docker Compose Development Environment Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docs/docker/docker.md Command to open a shell within the Docker Compose development environment for debugging purposes. This allows direct interaction with the running container. ```bash DOCKER_BUILDKIT=1 docker-compose -f ./docker-compose.nextjs-app.yml run --rm develop sh ``` -------------------------------- ### Run Playwright Tests Inside Docker Container Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/apps/nextjs-app/e2e/README.md Once inside the Docker container, these commands are used to install dependencies and execute Playwright end-to-end tests using a specified configuration file. ```bash yarn install cd apps/nextjs-app/e2e npx playwright test --config $PWD/playwright.config.ts ``` -------------------------------- ### Launch Docker Container for Playwright Tests Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/apps/nextjs-app/e2e/README.md This command sets up the Playwright version and launches a Docker container with necessary configurations to run tests. It maps the current directory into the container and sets the working directory. ```bash export PLAYWRIGHT_VERSION=$(npm ls @playwright/test | grep '@playwright/test@' | grep -v 'deduped' | sed 's/.*@//' | uniq -u) docker run -it --rm --ipc=host --add-host=host.docker.internal:host-gateway -v $PWD:/app -w /app mcr.microsoft.com/playwright:v${PLAYWRIGHT_VERSION}-jammy /bin/bash ``` -------------------------------- ### GraphQL Query Execution Example (Bash) Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Demonstrates how to query the GraphQL API endpoint using curl. This example shows a POST request to '/api/graphql' with a JSON payload containing a GraphQL query to fetch poems, including their details and associated keywords. It also shows the expected JSON response structure. ```bash # Query poems via GraphQL curl -X POST http://localhost:3000/api/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "query GetPoems { poems(limit: 5) { id title author content keywords { name } } }" }' # Expected Response: # { # "data": { # "poems": [ # { # "id": 1, # "title": "The Road Not Taken", # "author": "Robert Frost", # "content": "Two roads diverged...", # "keywords": [ # { "name": "nature" }, # { "name": "choices" } # ] # } # ] # } # } ``` -------------------------------- ### Running Tasks with Turborepo CLI Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Provides examples of command-line interfaces for executing tasks across the monorepo using Turborepo. It demonstrates building all packages, running tests on affected workspaces, linting specific packages, executing multiple tasks in parallel, and cleaning the Turborepo cache. ```bash # Build all packages and apps turbo run build # Run tests in affected workspaces only turbo run test --filter=...@origin/main # Run linting with specific scope turbo run lint --filter=@your-org/core-lib # Run multiple tasks in parallel turbo run build test lint # Clear turbo cache turbo clean ``` -------------------------------- ### Example package.json for a New Package Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/README.md This JSON object defines the structure and scripts for a new package's package.json file. It includes essential fields like name, version, and scripts for cleaning, linting, type checking, and testing. ```json { "name": "@your-org/magnificent-poney", "version": "0.0.0", "private": true, "scripts": { "clean": "rimraf ./tsconfig.tsbuildinfo", "lint": "eslint . --ext .ts,.tsx,.js,.jsx", "typecheck": "tsc --project ./tsconfig.json --noEmit", "test": "run-s 'test:*'", "test:unit": "echo \"No tests yet\"", "fix:staged-files": "lint-staged --allow-empty", "fix:all-files": "eslint . --ext .ts,.tsx,.js,.jsx --fix" }, "devDependencies": { "@your-org/eslint-config-bases": "workspace:^" } } ``` -------------------------------- ### GraphQL Query Example Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/apps/nextjs-app/README.md This is an example GraphQL query to fetch user data. It demonstrates how to interact with the GraphQL API exposed by the application. ```graphql query { getUser(id: 1) { id email } } ``` -------------------------------- ### Develop Next.js App with Docker Compose Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docs/docker/docker.md Command to run the Next.js application in development mode using Docker Compose. It utilizes multi-stage builds and specifies compose files for the Next.js app and general services like PostgreSQL. ```bash yarn docker:nextjs-app:develop # Or alternatively DOCKER_BUILDKIT=1 docker-compose -f ./docker-compose.yml -f ./docker-compose.nextjs-app.yml up develop main-db ``` -------------------------------- ### Add Workspace Dependency for common-i18n Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/packages/common-i18n/README.md Installs the common-i18n package as a workspace dependency in your consuming application or package. This ensures that the monorepo's shared translation package is correctly linked. ```bash yarn add @your-org/common-locales:"workspace:^" ``` -------------------------------- ### Docker Compose Configuration for Multi-Service Deployment Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Provides a docker-compose.yml file to define and manage multi-container Docker applications. This example sets up services for the Next.js app and a PostgreSQL database, including port mappings, environment variables, dependencies, and volume persistence for the database data. It also includes commands to manage the compose stack. ```yaml # docker-compose.yml version: '3.8' services: app: build: context: . dockerfile: docker/Dockerfile ports: - '3000:3000' environment: - PRISMA_DATABASE_URL=postgresql://postgres:password@db:5432/mydb depends_on: - db db: image: postgres:15 environment: POSTGRES_PASSWORD: password POSTGRES_DB: mydb ports: - '5432:5432' volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data: ``` ```bash # Start all services docker-compose up -d # View logs docker-compose logs -f app # Stop services docker-compose down ``` -------------------------------- ### Creating a New Package in Monorepo (Bash) Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Provides bash commands to create a new package directory within a monorepo, initialize its `package.json` with essential scripts (clean, lint, typecheck, test, fix), and set up a basic `tsconfig.json` extending a base configuration. Assumes `rimraf`, `eslint`, `tsc`, and `vitest` are available in the environment. ```bash # Create new package directory mkdir packages/my-package cd packages/my-package # Create package.json cat > package.json << 'EOF' { "name": "@your-org/my-package", "version": "0.0.0", "private": true, "main": "./src/index.ts", "types": "./src/index.ts", "scripts": { "clean": "rimraf ./tsconfig.tsbuildinfo", "lint": "eslint . --ext .ts,.tsx,.js,.jsx", "typecheck": "tsc --project ./tsconfig.json --noEmit", "test": "vitest run", "fix:all-files": "eslint . --ext .ts,.tsx,.js,.jsx --fix" }, "devDependencies": { "@your-org/eslint-config-bases": "workspace:^" } } EOF # Create tsconfig.json cat > tsconfig.json << 'EOF' { "extends": "../../tsconfig.base.json", "compilerOptions": { "outDir": "./dist", "rootDir": "./src" }, "include": ["src/**/*"] } EOF ``` -------------------------------- ### Turborepo Configuration for Monoreorepo Tasks Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Defines the build system and task pipeline for the monorepo using Turborepo. The turbo.json file specifies global dependencies, task configurations (like build outputs and linting environments), and caching strategies. This setup optimizes build performance by leveraging a remote cache and selective task execution. ```json // turbo.json { "$schema": "https://turbo.build/schema.json", "globalDependencies": ["**/.env.*local", "**/tsconfig*.json"], "tasks": { "build": { "outputs": ["dist/**"] }, "test-unit": {}, "lint": { "env": ["TIMING"] }, "typecheck": {}, "codegen": { "cache": true, "outputs": ["src/generated/**"] } } } ``` -------------------------------- ### ESLint Configuration for Monorepo with TypeScript and React Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Shows an example ESLint configuration file for a monorepo workspace. It extends shared configurations for TypeScript, Sonar, RegExp, React, React Query, Jest, RTL, and Prettier, with options for custom rules. ```javascript // apps/my-app/.eslintrc.js require('@your-org/eslint-config-bases/patch/modern-module-resolution'); module.exports = { root: true, parserOptions: { tsconfigRootDir: __dirname, project: 'tsconfig.json', }, ignorePatterns: ['**/node_modules', '**/.cache', 'build', '.next'], extends: [ '@your-org/eslint-config-bases/typescript', '@your-org/eslint-config-bases/sonar', '@your-org/eslint-config-bases/regexp', '@your-org/eslint-config-bases/react', '@your-org/eslint-config-bases/react-query', '@your-org/eslint-config-bases/jest', '@your-org/eslint-config-bases/rtl', '@your-org/eslint-config-bases/prettier-plugin', ], rules: { // Custom rules for your workspace }, }; ``` -------------------------------- ### Configure ESLint with Base Configurations Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/packages/eslint-config-bases/README.md Demonstrates how to configure ESLint in a workspace's .eslintrc.js or .eslintrc.cjs file. It shows how to extend various base configurations provided by @your-org/eslint-config-bases, including typescript, sonar, react, and prettier. The example also includes a note about module resolution patching for monorepos and how to specify root project settings and ignore patterns. ```javascript require("@your-org/eslint-config-bases/patch/modern-module-resolution"); module.exports = { root: true, parserOptions: { tsconfigRootDir: __dirname, project: "tsconfig.json", }, ignorePatterns: ["**/node_modules", "**/.cache", "build", ".next"], extends: [ "@your-org/eslint-config-bases/typescript", "@your-org/eslint-config-bases/sonar", "@your-org/eslint-config-bases/regexp", "@your-org/eslint-config-bases/react", "@your-org/eslint-config-bases/react-query", "@your-org/eslint-config-bases/jest", "@your-org/eslint-config-bases/rtl", // "@your-org/eslint-config-bases/mdx", // "@your-org/eslint-config-bases/graphql-schema", // "@your-org/eslint-config-bases/storybook", // "@your-org/eslint-config-bases/playwright", "@your-org/eslint-config-bases/prettier-plugin", // "@your-org/eslint-config-bases/prettier-config", ], rules: { // Specific global rules for your app or package }, overrides: [ // Specific file rules for your app or package ], }; ``` -------------------------------- ### Internationalization Setup with common-i18n (TypeScript) Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Illustrates setting up internationalization (i18n) using a custom 'common-i18n' package within a Next.js application. It defines multilingual resources and demonstrates how to use the 'useTranslation' hook from 'next-i18next' to access translated strings in components. Requires the 'next-i18next' library. ```typescript // packages/common-i18n/src/index.ts import type { I18nResources } from '@your-org/common-i18n'; // Define multilingual resources const resources: I18nResources = { en: { common: { welcome: 'Welcome', logout: 'Logout', }, }, fr: { common: { welcome: 'Bienvenue', logout: 'Déconnexion', }, }, }; // Use in Next.js application import { useTranslation } from 'next-i18next'; function Header() { const { t } = useTranslation('common'); return (

{t('welcome')}

); } ``` -------------------------------- ### Prettier Configuration with Shared Helpers Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Demonstrates a Prettier configuration file that utilizes shared helpers to extend the base configuration. It includes an example of overriding specific file formats, like JSON. ```javascript // .prettierrc.js const { getPrettierConfig } = require('@your-org/eslint-config-bases/helpers'); module.exports = { ...getPrettierConfig(), overrides: [ { files: '*.json', options: { tabWidth: 2, }, }, ], }; ``` -------------------------------- ### Run CI Packages Workflow in GitHub Actions Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt This workflow runs on pushes to the main branch and pull requests, triggering on changes to packages, package.json, or yarn.lock. It checks out code, sets up Node.js with caching, installs dependencies immutably, and runs linting, type checking, unit tests, and builds. ```yaml name: CI Packages on: push: branches: [main] paths: - 'packages/**' - 'package.json' - 'yarn.lock' pull_request: jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node.js uses: actions/setup-node@v3 with: node-version: '18' cache: 'yarn' - name: Install dependencies run: yarn install --immutable - name: Lint run: yarn g:lint - name: Type check run: yarn g:typecheck - name: Test run: yarn g:test-unit - name: Build run: yarn g:build ``` -------------------------------- ### Database Operations with Prisma Client (TypeScript) Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Demonstrates how to use the Prisma client for database operations in a Next.js application. It includes fetching data (poems), creating new records (posts), and performing atomic transactions. Requires Prisma client setup and a PostgreSQL database connection. ```typescript // Import Prisma client and types import { PrismaClientDbMain, PrismaDbMain, PrismaManager } from '@your-org/db-main-prisma'; // Create a development-safe Prisma instance (avoids connection exhaustion) const prisma = PrismaManager.getDevSafeInstance( 'default', () => new PrismaClientDbMain({ log: ['query', 'info', 'warn', 'error'], }) ); // Query poems from database async function getPoems() { const poems = await prisma.poem.findMany({ include: { keywords: { include: { keyword: true, }, }, }, orderBy: { createdAt: 'desc', }, take: 10, }); return poems; } // Create a new post async function createPost(data: { slug: string; title: string; content: string; authorId: number; }) { const post = await prisma.post.create({ data: { ...data, publishedAt: new Date(), }, include: { author: true, }, }); return post; } // Use transactions for atomic operations async function transferData() { await prisma.$transaction(async (tx) => { const user = await tx.user.create({ data: { username: 'john_doe', email: 'john@example.com', role: 'USER', }, }); await tx.post.create({ data: { slug: 'first-post', title: 'My First Post', content: 'Hello World', authorId: user.id, }, }); }); } ``` -------------------------------- ### Install @your-org/ts-utils with Yarn Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/packages/ts-utils/README.md Instructions for installing the @your-org/ts-utils package using Yarn, specifying a workspace version for monorepo compatibility. ```bash yarn add @your-org/ts-utils"@workspace:^" ``` -------------------------------- ### Install ESLint Dependencies Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/packages/eslint-config-bases/README.md Installs the necessary ESLint core package and the custom eslint-config-bases package as development dependencies. It also lists optional dependencies for specific plugins like graphql, mdx, and tailwind, which are only required if those features are utilized. ```bash yarn add --dev eslint @your-org/eslint-config-bases # Optional dependencies for specific plugins: yarn add --dev @graphql-eslint/eslint-plugin yarn add --dev eslint-plugin-mdx yarn add --dev eslint-plugin-tailwindcss ``` -------------------------------- ### Update Dependencies (Bash) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/CONTRIBUTING.md Applies possible dependency updates. After running this command, it's recommended to run `yarn install` and `yarn dedupe`. ```bash yarn deps:update --dep dev ``` -------------------------------- ### Unit Testing with Vitest Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Demonstrates unit testing for a TypeScript utility library using Vitest. The example shows how to import Vitest functions (`describe`, `it`, `expect`) and test specific methods of an `ArrayUtils` class, including checking for random item selection and item removal from an array. ```typescript // packages/ts-utils/src/array/ArrayUtils.test.ts import { describe, it, expect } from 'vitest'; import { ArrayUtils } from './ArrayUtils'; describe('ArrayUtils', () => { it('should get random item from array', () => { const items = ['a', 'b', 'c'] as const; const result = ArrayUtils.getRandom(items); expect(items).toContain(result); }); it('should remove item from array', () => { const arr = [1, 2, 3, 4, 5]; const result = ArrayUtils.removeItem(arr, 3); expect(result).toEqual([1, 2, 4, 5]); expect(result).not.toContain(3); }); }); ``` -------------------------------- ### End-to-End Testing with Playwright Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Illustrates end-to-end testing for a Next.js application using Playwright. The example spec file defines tests for the homepage, verifying the presence of a welcome message and the navigation flow to the login page after clicking a 'Login' button. It also covers setting up Playwright browsers and running tests from the command line. ```typescript // apps/nextjs-app/e2e/pages/index/index.spec.ts import { test, expect } from '@playwright/test'; test.describe('Homepage', () => { test('should display welcome message', async ({ page }) => { await page.goto('/'); const heading = page.locator('h1'); await expect(heading).toContainText('Welcome'); }); test('should navigate to login page', async ({ page }) => { await page.goto('/'); await page.click('text=Login'); await expect(page).toHaveURL('/auth/login'); const loginForm = page.locator('form'); await expect(loginForm).toBeVisible(); }); }); ``` ```bash # Install Playwright browsers yarn install:playwright # Run E2E tests yarn g:test-e2e # Run E2E tests in specific workspace cd apps/nextjs-app yarn test-e2e # Run in headed mode with UI yarn playwright test --headed --ui ``` -------------------------------- ### Build and Run Docker Image for Next.js App Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Explains how to build a Docker image for the Next.js application and run it as a container. It includes the `docker build` command with tagging and a `docker run` command that maps ports and sets environment variables, such as the database connection URL. ```bash # Build Next.js app Docker image docker build -t nextjs-app:latest -f docker/Dockerfile . # Run container docker run -p 3000:3000 \ -e PRISMA_DATABASE_URL="postgresql://..." nextjs-app:latest ``` -------------------------------- ### Example Build Environment Variables (.env) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/apps/nextjs-app/src/lib/env/README.md Demonstrates the format of environment variables used for the build process. These variables are typically loaded from a `.env` file and are then validated by the `getValidatedBuildEnv` utility. Examples include settings for output mode and type checking. ```dotenv # File: ./env NEXT_BUILD_ENV_OUTPUT=classic NEXT_BUILD_ENV_TYPECHECK=1 ``` -------------------------------- ### Global Monorepo Scripts with Yarn Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Provides essential global scripts for managing monorepo tasks. These scripts allow for building, type-checking, linting, testing (unit and E2E), code generation, cleaning, and dependency management across all workspaces. ```bash # Run builds across all workspaces yarn g:build # Type-check all workspaces yarn g:typecheck # Lint all workspaces with timing information yarn g:lint # Run all unit tests yarn g:test-unit # Run all e2e tests yarn g:test-e2e # Generate code (Prisma, GraphQL, etc.) across workspaces yarn g:codegen # Clean all build artifacts and caches yarn g:clean # Check for dependency updates yarn deps:check --dep dev # Apply dependency updates yarn deps:update --dep dev ``` -------------------------------- ### Inspect, Save, Load, and Run Docker Images for Next.js App Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/docker/README.md This section details Docker commands for managing the Next.js application image. It includes inspecting image details, saving the image in different compressed formats (gzip and zstd for faster compression), loading a saved image, and running the image as a container. ```bash export IMAGE=nextjs-monorepo-example-nextjs-app # Inspect the image docker image inspect ${IMAGE} # Save te image (gzip) docker save ${IMAGE} | gip > /tmp/${IMAGE}-app.tar.gz # +/- 70M ${IMAGE}.tar.gz (slower) docker save ${IMAGE} | zstd | pv > /tmp/${IMAGE}.tar.zst # +/- 60M Jul 20 10:54 ${IMAGE}.tar.zst (faster) # if not using k8s/registry, you can load and run from a remote machine. docker load -i /tmp/${IMAGE}.tar.zst # Run the image docker run ${IMAGE} ``` -------------------------------- ### Database Management (db-main-prisma) Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt APIs for managing the main database using Prisma. This includes functions to query poems, create posts, and perform transactional operations. ```APIDOC ## Database Management (db-main-prisma) ### Description Provides functions to interact with the main database using Prisma. Supports querying poems, creating posts, and executing atomic transactions. ### Functions - **getPoems()**: Queries the database for the latest 10 poems, including their associated keywords. - **createPost(data)**: Creates a new post with the provided data (slug, title, content, authorId) and returns the created post with author information. - **transferData()**: Executes a database transaction to atomically create a new user and their first post. ``` -------------------------------- ### Publish Packages with Changesets Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Details the commands for publishing packages managed by Changesets. It includes building all packages first using `yarn g:build`, followed by `yarn g:release`, which automates the process of updating package versions, generating changelogs, and creating git tags according to the defined changesets. ```bash # Build all packages yarn g:build # Publish packages (updates versions and creates git tags) yarn g:release ``` -------------------------------- ### Build Documentation (Bash) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/CONTRIBUTING.md Rebuilds the API documentation for the project. This script should be run to update documentation as part of the contribution checklist. ```bash yarn g:build-doc ``` -------------------------------- ### Build All Workspaces (Bash) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/CONTRIBUTING.md Runs the build process for all packages in the monorepo. This is a fundamental script for preparing the project for deployment or further checks. ```bash yarn g:build ``` -------------------------------- ### TypeScript Utilities for Array and Type Guards Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Illustrates the usage of shared TypeScript utilities for array manipulation (getting random items, removing items) and type guards for safe type checking. These utilities enhance code safety and readability. ```typescript import { ArrayUtils } from '@your-org/ts-utils'; // Get random item from array const colors = ['red', 'green', 'blue'] as const; const randomColor = ArrayUtils.getRandom(colors); console.log(randomColor); // Output: 'green' (random) // Remove item from array const numbers = [1, 2, 3, 4, 5]; const filtered = ArrayUtils.removeItem(numbers, 3); console.log(filtered); // Output: [1, 2, 4, 5] // Import type guards import { isString, isNumber } from '@your-org/ts-utils'; const value: unknown = 'hello'; if (isString(value)) { console.log(value.toUpperCase()); // Type-safe: 'HELLO' } // Import conversion utilities import { convertToBoolean, convertToNumber } from '@your-org/ts-utils'; const bool = convertToBoolean('true'); // true const num = convertToNumber('42'); // 42 ``` -------------------------------- ### Custom Storybook Styling Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/packages/ui-lib/src/_stories/Introduction.mdx This snippet defines custom CSS styles for the Storybook documentation page. It includes styles for headings, link lists, individual link items, and tip elements, enhancing the visual presentation of the introduction. These styles are embedded directly using a template literal within a style tag. ```css ``` -------------------------------- ### Check Build File Size Limits (Bash) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/CONTRIBUTING.md Ensures that the built distribution files are within the defined size limits. This script requires `g:build` to be run first. ```bash yarn g:check-size ``` -------------------------------- ### Increase File Watcher Limit (Bash) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/TROUBLESHOOT.md This command updates the system's configuration to increase the maximum number of file watchers allowed. This is necessary to overcome the 'ENOSPC: System limit for number of file watchers reached' error commonly encountered in development environments with many files. ```bash # insert the new value into the system config echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p # check that the new value was applied cat /proc/sys/fs/inotify/max_user_watches # config variable name (not runnable) fs.inotify.max_user_watches=524288 ``` -------------------------------- ### Storybook Meta Configuration Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/packages/ui-lib/src/_stories/Introduction.mdx This snippet configures Storybook's meta information for the documentation page. It specifies the title that will appear in the Storybook UI sidebar. It relies on the '@storybook/blocks' package. ```jsx import { Meta } from '@storybook/blocks'; ``` -------------------------------- ### Internationalization (common-i18n) Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Internationalization resources and usage example for the common i18n module. ```APIDOC ## Internationalization (common-i18n) ### Description Manages multilingual resources for the application. Provides a way to define translations for different languages and use them within components. ### Usage - **resources**: An object containing translation keys organized by language (e.g., 'en', 'fr'). - **useTranslation**: Hook from 'next-i18next' to access translation functions within Next.js components. ``` -------------------------------- ### Run Unit Tests (Bash) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/CONTRIBUTING.md Executes unit tests across all workspaces in the monorepo. This script should be run as part of the contribution checklist to ensure code quality. ```bash yarn g:test-unit ``` -------------------------------- ### Check for Upgradable Dependencies (Bash) Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/CONTRIBUTING.md Identifies packages that can be upgraded globally. This script utilizes the configuration in `.ncurc.yml`. ```bash yarn deps:check --dep dev ``` -------------------------------- ### Consume isPlainObject Utility from @your-org/ts-utils Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/packages/ts-utils/README.md Example demonstrating how to import and use the `isPlainObject` typeguard function from the @your-org/ts-utils package in TypeScript. ```typescript import { isPlainObject } from "@your-org/ts-utils"; isPlainObject(true) === false; ``` -------------------------------- ### GraphQL API Endpoint Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt The main GraphQL API endpoint for the Next.js application, configured with various security plugins and options. ```APIDOC ## GraphQL API Endpoint ### Description This endpoint serves the GraphQL API for the Next.js application. It is configured with security measures like rate limiting, depth limiting, and cost limiting. ### Method POST, GET ### Endpoint `/api/graphql` ### Parameters #### Query Parameters - **query** (string) - Required - The GraphQL query string. - **variables** (object) - Optional - Variables for the GraphQL query. #### Request Body - **query** (string) - Required - The GraphQL query string. - **variables** (object) - Optional - Variables for the GraphQL query. ### Request Example ```bash curl -X POST http://localhost:3000/api/graphql \ -H "Content-Type: application/json" \ -d '{ "query": "query GetPoems { poems(limit: 5) { id title author content keywords { name } } }" }' ``` ### Response #### Success Response (200) - **data** (object) - The result of the GraphQL query. - **errors** (array) - An array of errors, if any occurred during query execution. #### Response Example ```json { "data": { "poems": [ { "id": 1, "title": "The Road Not Taken", "author": "Robert Frost", "content": "Two roads diverged...", "keywords": [ { "name": "nature" }, { "name": "choices" } ] } ] } } ``` ``` -------------------------------- ### Monorepo Dependencies in package.json Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/apps/nextjs-app/README.md This JSON snippet shows the dependencies of the Next.js app that are sourced from within the monorepo. It uses 'workspace:*' to reference local packages. ```json { "dependencies": { "@your-org/core-lib": "workspace:*", "@your-org/db-main-prisma": "workspace:*", "@your-org/ui-lib": "workspace:*" } } ``` -------------------------------- ### Create a Changeset for Versioning Source: https://context7.com/belgattitude/nextjs-monorepo-example/llms.txt Illustrates the process of creating a changeset to manage package versions and changelogs within the monorepo. It involves running a command to initiate an interactive prompt where users select packages, choose version bumps (major, minor, patch), and write release summaries. The output is a markdown file in the .changeset directory. ```bash # Add a changeset for your changes yarn g:changeset # Follow interactive prompts: # - Select changed packages # - Choose version bump type (major/minor/patch) # - Write a summary of changes # Changeset file created at .changeset/random-name.md ``` ```markdown --- '@your-org/core-lib': minor '@your-org/ui-lib': patch --- Add new utility function for date formatting and fix button styling bug ``` -------------------------------- ### Configure tsconfig.json Paths for common-i18n Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/packages/common-i18n/README.md Configures TypeScript path aliases in your application's tsconfig.json file. This allows you to import from the @your-org/common-i18n package and its locales directory directly within your project. ```json { "compilerOptions": { "paths": { "@your-org/common-i18n": ["../../../packages/common-i18n/src/index"], "@your-org/common-i18n/locales/*": [ "../../../packages/common-i18n/src/locales/*" ] } } } ``` -------------------------------- ### TypeScript Path Aliases in tsconfig.json Source: https://github.com/belgattitude/nextjs-monorepo-example/blob/main/apps/nextjs-app/README.md This JSON snippet configures TypeScript path aliases in the local tsconfig.json file. These aliases are crucial for resolving monorepo packages correctly within the application. ```json { "compilerOptions": { "baseUrl": "./src", "paths": { "@your-org/ui-lib/*": ["../../../packages/ui-lib/src/*"], "@your-org/ui-lib": ["../../../packages/ui-lib/src/index"], "@your-org/core-lib/*": ["../../../packages/core-lib/src/*"], "@your-org/core-lib": ["../../../packages/core-lib/src/index"], "@your-org/db-main-prisma/*": ["../../../packages/db-main-prisma/src/*"], "@your-org/db-main-prisma": [ "../../../packages/db-main-prisma/src/index" ] } } } ```