Comprehensive development rules for Next.js 14 chat application with TypeScript, Tailwind CSS, and file-based storage. Covers code style, security, testing, documentation, and best practices for App Router architecture.
A comprehensive development guide for building a Next.js 14 chat application using TypeScript, Tailwind CSS, and file-based storage with the App Router architecture.
This guide covers development practices for a Next.js 14 chat application featuring:
1. **Type Safety**
- Always enable and use TypeScript strict mode
- Prefer explicit types over `any` - use `unknown` if type is truly unknown
- Use interfaces from `@/types` for shared data structures (User, Message, Attachment, etc.)
- Export types and interfaces from `types/index.ts` for shared usage
- Use async/await over promise chains
- Handle errors explicitly with try-catch blocks
- Never bypass TypeScript type checking
2. **Type Definition Patterns**
```typescript
// Good
interface User {
id: string;
username: string;
email: string;
}
// Avoid
const user: any = { ... };
```
1. **Component Strategy**
- Use Server Components by default
- Only add 'use client' when client-side interactivity is required
- Place Server Actions in separate files or at bottom of Server Components
- Use `async` Server Components for data fetching
- Use `cookies()` from 'next/headers' for cookie management in Server Components
- Prefer Server Actions over API routes when possible
2. **API Routes**
- Place in `app/api/` directory following REST conventions
- Return appropriate HTTP status codes
- Provide user-friendly error messages
- Log errors server-side for debugging
3. **Route Protection**
- Use `getSession()` from `lib/auth.ts` in Server Components
- Use `setSession()` and `clearSession()` for login/logout
- Protect routes by checking session in page components or middleware
1. **Directory Structure**
- `lib/` - Reusable utilities
- `types/index.ts` - Type definitions
- `app/api/[route]/route.ts` - API routes
- `app/[page]/page.tsx` - Page components
- `components/` - Shared components
- Use path alias: `@/*` maps to project root
2. **Naming Conventions**
- Components: PascalCase (e.g., `ChatMessage.tsx`)
- Pages/routes: kebab-case
- Utilities: camelCase
- Constants: UPPER_SNAKE_CASE
- Types/Interfaces: PascalCase
1. **Function Design**
- Keep functions small and single-purpose
- Extract reusable logic into utility functions in `lib/`
- Use meaningful variable and function names
- Add JSDoc comments for complex functions
- Handle edge cases and error scenarios
- Validate user input on both client and server side
2. **JSDoc Format**
```typescript
/**
* Verifies user password against stored hash
* @param username - The username to verify
* @param password - The plain text password
* @returns Promise resolving to true if password matches
* @throws {Error} If user lookup fails
*/
export async function verifyPassword(username: string, password: string): Promise<boolean>
```
1. **Authentication & Secrets**
- Never expose JWT_SECRET or secrets in code - use environment variables
- Use httpOnly cookies for session tokens
- Use bcrypt for password hashing
- Always validate and sanitize user input
- Implement proper error handling that doesn't leak sensitive information
2. **File Upload Security**
- Validate file types and sizes before saving
- Sanitize file names
- Store uploads outside public directory when possible
1. **File Operations**
- Use utilities from `lib/storage.ts`
- Always ensure data directory exists before operations
- Handle file system errors gracefully
- Validate data when reading from JSON files
- Use `readUsers()`, `readMessages()`, `appendMessage()` patterns
- Call `ensureDataDir()` or use auto-handling functions
1. **CSS Guidelines**
- Use Tailwind utility classes
- Follow mobile-first responsive design
- Keep custom CSS in `app/globals.css` minimal
- Use Tailwind design tokens consistently (colors, spacing)
1. **Best Practices**
- Use Server Components to reduce client-side JavaScript
- Implement proper loading states and error boundaries
- Optimize images using Next.js Image component
- Consider pagination for message history
- Use React.memo for expensive components if needed
1. **ESLint Requirements**
- Run `npm run lint` before committing
- Fix all linting errors before submission
- Use `// eslint-disable-next-line` sparingly with justification
- Remove unused variables or prefix with underscore (`_unusedVar`)
- Remove console.log in production code
- Group imports: external → internal → relative, alphabetically
2. **Pre-commit Checks**
- Run `npm run lint` locally
- Ensure TypeScript compiles: `tsc --noEmit`
- Remove or replace console.log with proper logging
1. **Test Organization**
- Place test files next to source: `lib/auth.test.ts` for `lib/auth.ts`
- Or use `__tests__` directory
- Use descriptive test file names
- Follow AAA pattern: Arrange, Act, Assert
2. **Testing Frameworks**
- Unit/Integration: Jest with React Testing Library
- API Testing: Jest with fetch/mock requests
- E2E: Playwright or Cypress
3. **Test Structure Example**
```typescript
describe('verifyPassword', () => {
it('should return true for correct password', async () => {
// Arrange
const username = 'user1';
const password = 'user1pass';
// Act
const result = await verifyPassword(username, password);
// Assert
expect(result).toBe(true);
});
});
```
4. **Testing Best Practices**
- Mock external dependencies (file system, APIs, cookies)
- Test edge cases: empty inputs, null values, boundaries
- Test error scenarios: invalid inputs, failures
- Keep tests isolated and independent
- Use meaningful assertions (`toBe`, `toEqual`)
- Clean up mocks and test data after each test
- Aim for high coverage on critical paths (auth, storage, API)
- Don't aim for 100% coverage - focus on meaningful tests
5. **Running Tests**
- Run tests: `npm test`
- Watch mode: `npm test -- --watch`
- Coverage: `npm test -- --coverage`
- Specific file: `npm test auth.test.ts`
1. **Code Documentation**
- Add JSDoc for all exported functions, classes, and utilities
- Document complex types and interfaces
- Use inline comments to explain "why", not "what"
- Write self-documenting code with clear names
2. **README Documentation**
- Keep README.md updated with:
- Project setup instructions
- Environment variables required
- Development server instructions
- Production build process
- Project structure overview
- Key features and usage
3. **API Documentation**
- Document all API routes with:
- HTTP method and endpoint
- Request body/query parameters
- Response format
- Error responses
- Authentication requirements
4. **Component Documentation**
- Document complex components with:
- Purpose and usage
- Props interface
- Example usage
- Special behavior or side effects
1. **Feature Development Checklist**
- Check if types need to be added to `types/index.ts`
- Create utility functions in `lib/` if reusable
- Use Server Components unless client interactivity required
- Follow existing authentication and session patterns
- Update type definitions before implementation
- Write tests for critical logic
- Document public APIs and complex logic
```typescript
// Server Component
import { getSession } from '@/lib/auth';
import { redirect } from 'next/navigation';
export default async function DashboardPage() {
const session = await getSession();
if (!session) redirect('/login');
return <Dashboard user={session.user} />;
}
```
```typescript
import { readMessages, appendMessage, ensureDataDir } from '@/lib/storage';
export async function saveMessage(message: Message) {
await ensureDataDir();
await appendMessage(message);
}
```
```typescript
'use server';
import { revalidatePath } from 'next/cache';
export async function createMessage(formData: FormData) {
const content = formData.get('content') as string;
// Validate and save
await saveMessage({ content, timestamp: Date.now() });
revalidatePath('/chat');
}
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/nextjs-14-tempchat-development-guide/raw