);
}
```
--------------------------------
### 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"
]
}
}
}
```