Skip to main content

TypeScript Next.js Basic Archetype

Modern full-stack Next.js application with TypeScript, Tailwind CSS, and production-ready deployment configuration

Generate a comprehensive Next.js application built with TypeScript, featuring the latest App Router, server components, modern styling with Tailwind CSS, and optimized deployment strategies for various platforms.

Overview

The typescript-nextjs-basic archetype creates a production-ready Next.js application using the latest features and best practices for modern web development.

Key Characteristics

  • Framework: Next.js 14+ with App Router and Server Components
  • Language: TypeScript with strict type checking
  • Styling: Tailwind CSS with custom design system
  • Performance: Optimized builds with automatic code splitting
  • Deployment: Vercel, Netlify, and custom deployment support
  • Development: Hot reloading, ESLint, Prettier integration

Technology Stack

Modern Next.js Features

Next.js 14+

  • App Router with file-based routing
  • Server Components for improved performance
  • Server Actions for form handling
  • Streaming and Suspense boundaries
  • Built-in SEO optimization

TypeScript Integration

  • Strict type checking configuration
  • Type-safe API routes and components
  • Automatic type inference
  • Enhanced developer experience
  • Build-time error catching

Performance Features

  • Automatic code splitting
  • Image optimization with Next.js Image
  • Font optimization and loading
  • Bundle analyzer integration
  • Static generation and ISR support

Development Tools

Code Quality

  • ESLint with Next.js and TypeScript rules
  • Prettier for consistent code formatting
  • Husky for Git hooks and pre-commit checks
  • lint-staged for optimized pre-commit linting

Styling & UI

  • Tailwind CSS with custom configuration
  • CSS Modules support for component styles
  • Dark mode support with theme switching
  • Responsive design utilities and breakpoints

Security & Performance

  • Content Security Policy (CSP) headers
  • HTTPS enforcement and security headers
  • Bundle size optimization and analysis
  • Performance monitoring integration

Project Architecture

App Router Structure

Click to enlarge

Generated Project Structure

my-nextjs-app/
├── app/
│ ├── globals.css # Global styles with Tailwind
│ ├── layout.tsx # Root layout with providers
│ ├── page.tsx # Home page
│ ├── loading.tsx # Global loading UI
│ ├── error.tsx # Error boundary
│ ├── not-found.tsx # 404 page
│ │
│ ├── api/ # API routes
│ │ ├── auth/ # Authentication endpoints
│ │ └── users/ # User management
│ │
│ └── (dashboard)/ # Route groups
│ ├── layout.tsx # Dashboard layout
│ ├── page.tsx # Dashboard home
│ └── settings/ # Settings pages

├── components/
│ ├── ui/ # Reusable UI components
│ │ ├── button.tsx
│ │ ├── input.tsx
│ │ └── modal.tsx
│ ├── forms/ # Form components
│ └── layout/ # Layout components
│ ├── header.tsx
│ ├── navigation.tsx
│ └── footer.tsx

├── lib/
│ ├── utils.ts # Utility functions
│ ├── auth.ts # Authentication logic
│ ├── database.ts # Database configuration
│ └── validations.ts # Schema validations

├── styles/
│ └── globals.css # Global styles and Tailwind

├── public/
│ ├── images/
│ └── icons/

├── next.config.js # Next.js configuration
├── tailwind.config.js # Tailwind configuration
├── tsconfig.json # TypeScript configuration
└── package.json # Dependencies and scripts

Server Components & Performance

Server-Side Rendering Strategy

Server Components

  • Zero JavaScript bundle for server components
  • Direct database access in components
  • Automatic streaming and Suspense
  • SEO-optimized content rendering

Client Components

  • Interactive features with "use client"
  • State management with React hooks
  • Event handling and user interactions
  • Progressive enhancement patterns

Performance Optimization

Automatic Optimizations

  • Code splitting at the page and component level
  • Image optimization with WebP/AVIF support
  • Font optimization with automatic preloading
  • CSS optimization and critical CSS extraction

Build-time Optimizations

  • Static generation for public pages
  • Incremental Static Regeneration (ISR)
  • Bundle analysis and size optimization
  • Tree shaking and dead code elimination

Data Fetching & API

Modern Data Fetching Patterns

// Server Component data fetching
export default async function ProductsPage() {
// Direct database access in Server Components
const products = await getProducts();

return (
<div>
<h1>Products</h1>
<Suspense fallback={<ProductsSkeleton />}>
<ProductsList products={products} />
</Suspense>
</div>
);
}

// API Route with TypeScript
export async function GET(request: Request) {
try {
const products = await db.product.findMany();
return Response.json(products);
} catch (error) {
return Response.json(
{ error: 'Failed to fetch products' },
{ status: 500 }
);
}
}

// Client-side data fetching with SWR
'use client';
import useSWR from 'swr';

export default function ClientProducts() {
const { data, error, isLoading } = useSWR('/api/products', fetcher);

if (error) return <div>Failed to load</div>;
if (isLoading) return <div>Loading...</div>;

return <ProductGrid products={data} />;
}

API Route Architecture

RESTful API Design

  • Type-safe API routes with TypeScript
  • Request/response validation with Zod
  • Error handling and status codes
  • Middleware for authentication and logging

Database Integration

  • Prisma ORM with type generation
  • Database migrations and seeding
  • Connection pooling and optimization
  • Multi-database support configuration

Styling & Design System

Tailwind CSS Configuration

// tailwind.config.js
module.exports = {
content: [
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
'./app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {
colors: {
primary: {
50: '#eff6ff',
500: '#3b82f6',
600: '#2563eb',
700: '#1d4ed8',
},
gray: {
50: '#f9fafb',
100: '#f3f4f6',
900: '#111827',
},
},
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif'],
mono: ['JetBrains Mono', 'monospace'],
},
animation: {
'fade-in': 'fadeIn 0.5s ease-in-out',
'slide-up': 'slideUp 0.3s ease-out',
},
},
},
plugins: [
require('@tailwindcss/forms'),
require('@tailwindcss/typography'),
],
darkMode: 'class',
};

Component Design System

UI Components

  • Button variants with consistent styling
  • Form inputs with validation states
  • Modal and dialog components
  • Loading and skeleton components

Layout Components

  • Responsive navigation with mobile menu
  • Header and footer with brand consistency
  • Sidebar and dashboard layouts
  • Grid and card layout systems

Authentication & Security

Authentication Integration

// lib/auth.ts - NextAuth.js configuration
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import CredentialsProvider from 'next-auth/providers/credentials';

export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
CredentialsProvider({
name: 'credentials',
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
// Custom authentication logic
const user = await verifyCredentials(credentials);
return user || null;
},
}),
],
session: {
strategy: 'jwt',
},
pages: {
signIn: '/auth/signin',
signUp: '/auth/signup',
},
};

export default NextAuth(authOptions);

// Middleware for protected routes
export { default } from 'next-auth/middleware';
export const config = {
matcher: ['/dashboard/:path*', '/admin/:path*'],
};

Security Best Practices

Security Headers

  • Content Security Policy (CSP)
  • X-Frame-Options for clickjacking protection
  • HTTPS enforcement with HSTS
  • Cross-Origin Resource Sharing (CORS)

Data Protection

  • Input validation with Zod schemas
  • SQL injection prevention with Prisma
  • XSS protection with sanitization
  • CSRF protection with tokens

Development Workflow

Local Development Setup

# Generate the Next.js application
archetect render git@github.com:p6m-archetypes/typescript-nextjs-basic.archetype.git my-app

cd my-app

# Install dependencies
npm install

# Set up environment variables
cp .env.example .env.local
# Edit .env.local with your configuration

# Run database migrations (if using Prisma)
npx prisma migrate dev

# Start development server
npm run dev

# Open browser to http://localhost:3000

Available Scripts

Development Commands

npm run dev          # Start development server
npm run build # Create production build
npm run start # Start production server
npm run lint # Run ESLint
npm run type-check # Run TypeScript check

Quality & Testing

npm run test         # Run test suite
npm run test:watch # Run tests in watch mode
npm run analyze # Analyze bundle size
npm run format # Format code with Prettier

Deployment Options

Zero-Config Deployment

  • Automatic builds from Git commits
  • Global CDN with edge caching
  • Serverless functions for API routes
  • Preview deployments for pull requests

Production Features

  • Custom domain configuration
  • Environment variable management
  • Analytics and performance monitoring
  • Automatic HTTPS and security headers

Alternative Deployment Options

Netlify

  • Static site generation with ISR support
  • Edge functions for dynamic content
  • Form handling and identity management
  • Branch deploys and split testing

Docker & Kubernetes

  • Multi-stage Docker builds included
  • Kubernetes manifests for scaling
  • Health checks and readiness probes
  • Rolling updates and blue-green deployment

AWS/GCP/Azure

  • Static hosting with CloudFront/CloudFlare
  • Serverless deployment with Lambda/Functions
  • Container deployment with ECS/Cloud Run
  • Database integration with managed services

Advanced Features

Performance Monitoring

// lib/analytics.ts
import { Analytics } from '@vercel/analytics/react';
import { SpeedInsights } from '@vercel/speed-insights/next';

// Performance monitoring setup
export function PerformanceProvider({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<Analytics />
<SpeedInsights />
</>
);
}

// Custom performance tracking
export function trackPageView(url: string) {
if (typeof window !== 'undefined') {
window.gtag?.('config', 'GA_MEASUREMENT_ID', {
page_location: url,
});
}
}

// Web Vitals reporting
export function reportWebVitals(metric: any) {
console.log(metric);
// Send to analytics service
}

Progressive Web App Features

PWA Capabilities

  • Service worker for offline functionality
  • App manifest for installation
  • Push notifications support
  • Background sync for data updates

Mobile Experience

  • Touch-friendly navigation
  • Responsive design patterns
  • Fast loading with service worker
  • Native app-like experience

Best Practices & Guidelines

Code Organization

Component Architecture

  • Separate Server and Client Components clearly
  • Use TypeScript interfaces for prop definitions
  • Implement error boundaries for robust UX
  • Follow accessibility guidelines (WCAG 2.1)

Performance Guidelines

  • Optimize images with Next.js Image component
  • Use dynamic imports for code splitting
  • Implement proper caching strategies
  • Monitor Core Web Vitals metrics

This archetype provides a solid foundation for building modern, performant Next.js applications with TypeScript, featuring the latest Next.js capabilities and production-ready deployment configurations.