Skip to content

nati3514/Enterprise-NextJs-Starter-Setup

Repository files navigation

Enterprise Next.js Starter

A production-ready, scalable Next.js starter template with TypeScript, authentication, role-based access control, and modern UI components.

πŸš€ Features

Core Features

  • Next.js 15+ with App Router
  • TypeScript for type safety
  • Tailwind CSS for styling
  • Dark/Light Mode with next-themes
  • Responsive Design mobile-first approach

Authentication & Authorization

  • JWT-based authentication with access & refresh tokens
  • Auto-refresh token mechanism
  • Secure token storage
  • Dynamic Role-Based Access Control (RBAC)
    • Permission checking utilities
    • Protected routes and components
    • Conditional rendering based on roles/permissions

State Management

  • Zustand for lightweight, performant state management
  • Persistent auth state
  • Notification state management

API Integration

  • Axios instance with interceptors
  • Automatic token refresh
  • Global error handling
  • Request/response transformation

UI Components

  • Reusable components (Button, Input, Card, etc.)
  • Toast notifications with react-hot-toast
  • Theme switcher
  • Dashboard layout with sidebar and header

Code Quality

  • ESLint configuration
  • TypeScript strict mode
  • Organized folder structure
  • Clean architecture principles

πŸ“ Project Structure

enterprise-nextjs-starter/
β”œβ”€β”€ app/                      # Next.js app directory
β”‚   β”œβ”€β”€ dashboard/           # Dashboard page
β”‚   β”œβ”€β”€ login/               # Login page
β”‚   β”œβ”€β”€ settings/            # Settings page
β”‚   β”œβ”€β”€ unauthorized/        # 403 page
β”‚   β”œβ”€β”€ layout.tsx           # Root layout
β”‚   └── page.tsx             # Home page
β”œβ”€β”€ components/              # React components
β”‚   β”œβ”€β”€ auth/               # Auth-related components
β”‚   β”‚   β”œβ”€β”€ Can.tsx         # Permission-based rendering
β”‚   β”‚   └── ProtectedRoute.tsx
β”‚   β”œβ”€β”€ layout/             # Layout components
β”‚   β”‚   β”œβ”€β”€ DashboardLayout.tsx
β”‚   β”‚   β”œβ”€β”€ Header.tsx
β”‚   β”‚   └── Sidebar.tsx
β”‚   β”œβ”€β”€ providers/          # Context providers
β”‚   β”‚   β”œβ”€β”€ ThemeProvider.tsx
β”‚   β”‚   └── ToastProvider.tsx
β”‚   └── ui/                 # Reusable UI components
β”‚       β”œβ”€β”€ Button.tsx
β”‚       β”œβ”€β”€ Card.tsx
β”‚       β”œβ”€β”€ Input.tsx
β”‚       └── ThemeSwitcher.tsx
β”œβ”€β”€ hooks/                   # Custom React hooks
β”‚   β”œβ”€β”€ useAuth.ts          # Authentication hook
β”‚   └── usePermission.ts    # Permission checking hook
β”œβ”€β”€ lib/                     # Library code
β”‚   β”œβ”€β”€ api/                # API clients
β”‚   β”‚   β”œβ”€β”€ auth.ts
β”‚   β”‚   β”œβ”€β”€ client.ts       # Axios instance with interceptors
β”‚   β”‚   └── dashboard.ts
β”‚   └── utils/              # Utility functions
β”‚       β”œβ”€β”€ helpers.ts
β”‚       β”œβ”€β”€ permissions.ts
β”‚       └── token.ts
β”œβ”€β”€ store/                   # Zustand stores
β”‚   β”œβ”€β”€ authStore.ts
β”‚   └── notificationStore.ts
β”œβ”€β”€ types/                   # TypeScript type definitions
β”‚   └── index.ts
β”œβ”€β”€ config/                  # Configuration files
β”‚   └── constants.ts
└── middleware/              # Next.js middleware (future use)

πŸ› οΈ Setup Instructions

Prerequisites

  • Node.js 18+ and npm/yarn
  • Backend API running (or configure mock API)

Installation

  1. Clone and navigate to the project:

    cd enterprise-nextjs-starter
  2. Install dependencies:

    npm install
  3. Configure environment variables:

    cp .env.example .env.local

    Update .env.local with your backend API URL:

    NEXT_PUBLIC_API_BASE_URL=http://localhost:8000/api
  4. Run the development server:

    npm run dev
  5. Open your browser: Navigate to http://localhost:3000

Building for Production

npm run build
npm start

πŸ” Authentication Flow

Login Process

  1. User submits credentials on /login
  2. API returns user data with access and refresh tokens
  3. Tokens are stored in localStorage
  4. User is redirected to /dashboard
  5. Zustand store manages authentication state

Token Management

  • Access Token: Short-lived, sent with every API request
  • Refresh Token: Long-lived, used to obtain new access tokens
  • Auto-refresh: Tokens are automatically refreshed before expiration
  • Interceptors: Axios interceptors handle token injection and refresh

Protected Routes

<ProtectedRoute
  requiredPermissions={['user:read']}
  requiredRoles={['admin']}
>
  <YourComponent />
</ProtectedRoute>

πŸ›‘οΈ Role-Based Access Control (RBAC)

Permission Checking

Using the Can Component

<Can permission="user:create">
  <CreateUserButton />
</Can>

<Can permissions={["user:update", "user:delete"]} requireAll={false}>
  <UserActions />
</Can>

Using the usePermission Hook

const { hasPermission, hasRole, canPerformAction } = usePermission();

if (hasPermission('user:delete')) {
  // Show delete button
}

if (canPerformAction('posts', 'create')) {
  // Allow post creation
}

Permission Format

Permissions follow the resource:action pattern:

  • user:read - View users
  • user:create - Create users
  • user:update - Edit users
  • user:delete - Delete users
  • user:manage - Full user management

🎨 Theming

The app supports dark/light mode with automatic system preference detection.

Switching Themes

import { ThemeSwitcher } from '@/components/ui/ThemeSwitcher';

<ThemeSwitcher />

Using Theme Classes

<div className="bg-white dark:bg-gray-800">
  <p className="text-gray-900 dark:text-white">Content</p>
</div>

πŸ“‘ API Integration

Making API Calls

import { getDashboardStats } from '@/lib/api/dashboard';

const stats = await getDashboardStats();

Custom API Calls

import apiClient from '@/lib/api/client';

const response = await apiClient.get('/your-endpoint');
const data = await apiClient.post('/your-endpoint', { data });

πŸ”” Notifications

Using Toast Notifications

import toast from 'react-hot-toast';

toast.success('Operation successful!');
toast.error('Something went wrong!');
toast.loading('Processing...');

🧩 Adding New Features

Creating a New Page

  1. Create a new folder in app/ directory
  2. Add page.tsx file
  3. Wrap with ProtectedRoute if authentication is required
  4. Use DashboardLayout for consistent layout

Creating a New Component

  1. Create component file in appropriate components/ subdirectory
  2. Export from the file
  3. Use TypeScript for props interface
  4. Follow existing component patterns

Adding New API Endpoints

  1. Define endpoint in config/constants.ts
  2. Create service function in lib/api/
  3. Add TypeScript types in types/index.ts

πŸ“ Best Practices

State Management

  • Use Zustand for global state
  • Keep component state local when possible
  • Persist critical state (auth) to localStorage

Security

  • Never store sensitive data in localStorage (only tokens)
  • Always validate permissions on both client and server
  • Use environment variables for API URLs and secrets

Performance

  • Use React.memo for expensive components
  • Implement lazy loading for large pages
  • Optimize images with Next.js Image component

Code Organization

  • Group related files together
  • Use index files for clean exports
  • Follow consistent naming conventions
  • Add JSDoc comments for complex functions

🚒 Deployment

Vercel (Recommended)

npm install -g vercel
vercel

Docker

# Dockerfile example
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
CMD ["npm", "start"]

Environment Variables

Ensure all NEXT_PUBLIC_* variables are set in your deployment platform.

πŸ“š Tech Stack

  • Framework: Next.js 15+
  • Language: TypeScript
  • Styling: Tailwind CSS
  • State Management: Zustand
  • HTTP Client: Axios
  • Notifications: react-hot-toast
  • Theme: next-themes
  • Fonts: Geist Sans & Mono

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Write tests if applicable
  5. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License.

πŸ†˜ Support

For issues and questions:

  • Check existing documentation
  • Review example implementations
  • Consult the backend API documentation

🎯 Roadmap

  • Add unit tests with Jest
  • Implement E2E tests with Playwright
  • Add internationalization (i18n)
  • Create admin panel
  • Add data tables with filtering/sorting
  • Implement real-time features with WebSockets
  • Add analytics integration
  • Create CI/CD pipeline

Built with ❀️ for scalable enterprise applications

About

A production-ready, scalable Next.js starter template with TypeScript, authentication, role-based access control, and modern UI components.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages