### Start Development Server
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/installation
Launch the local development server.
```bash
npm run dev
```
--------------------------------
### Start Node.js Production Server
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
To run your Next.js application with server-side rendering, build the application and then start the Node.js production server.
```bash
# Build your application
npm run build
# Start the Node.js server
npm run start
```
--------------------------------
### Initialize Environment Variables
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/installation
Create the .env file from the provided example template.
```bash
cp .env.example .env
```
--------------------------------
### Install Project Dependencies
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/installation
Use npm to install all required project dependencies. The --force flag is required due to modern dependency constraints.
```bash
npm install --force
```
--------------------------------
### Setup Database with Prisma
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/installation
Generate the Prisma client and run migrations to synchronize the database schema.
```bash
# Generate Prisma client
npx prisma generate
# Run migrations (if needed)
npx prisma migrate dev
```
--------------------------------
### Install Dependencies
Source: https://docs.keenthemes.com/metronic-nextjs/guides/custom-auth
Command to update project dependencies after removal.
```bash
npm install
```
--------------------------------
### Build Metronic Next.js for Production
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
Navigate to your project directory and run the build command to create optimized files for deployment. Ensure dependencies are installed if necessary.
```bash
# Navigate to your project directory
cd your-nextjs-project
# Install dependencies (if needed)
npm install
# Build for production
npm run build
```
--------------------------------
### Test Production Build Locally
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
Run these commands to build your Next.js application for production and then start a local server to preview the build. Visit `http://localhost:3000` to view.
```bash
npm run build
npm run start
```
--------------------------------
### Switching Demo Layouts with SettingsProvider
Source: https://docs.keenthemes.com/metronic-nextjs/guides/layouts
Demonstrates how to switch between different demo layouts programmatically using the `useSettings` hook from a custom settings provider. This example shows switching to 'demo5'.
```javascript
'use client';
import { useSettings } from '@/providers/settings-provider';
function LayoutSwitcher() {
const { setOption } = useSettings();
// Change to Demo5 layout
const switchToDemo5 = () => {
setOption('layout', 'demo5');
};
return (
{/* Other layout options * /}
);
}
```
--------------------------------
### Example Translation File Structure (en.json)
Source: https://docs.keenthemes.com/metronic-nextjs/guides/internationalization
Organize translations in JSON files, typically named after the language code (e.g., `en.json`). This example shows a basic structure with common and auth-related translations.
```json
// Example: en.json
{
"common": {
"save": "Save",
"cancel": "Cancel",
"error": "Error"
},
"auth": {
"login": {
"title": "Sign in to your account",
"button": "Sign in"
}
}
}
```
--------------------------------
### Switch Layouts
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/starter-kits
Example of wrapping children with a specific layout component in the protected layout file.
```jsx
{children}
```
--------------------------------
### Deploy with Vercel CLI
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
Install the Vercel CLI globally and use the `vercel` command to deploy your Next.js application. Vercel automatically detects Next.js and optimizes build settings.
```bash
# Install Vercel CLI
npm install -g vercel
# Deploy
vercel
```
--------------------------------
### Supabase Connection String Format
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/supabase
Example format for a PostgreSQL connection string used to connect Prisma Client to a Supabase database.
```text
postgres://username:password@db.supabase.co:5432/dbname
```
--------------------------------
### Controlling Layout Options with SettingsProvider
Source: https://docs.keenthemes.com/metronic-nextjs/guides/layouts
Shows how to interact with layout options using the `useSettings` hook. This example retrieves the current sidebar collapse state and provides a button to toggle it for 'demo1'.
```javascript
'use client';
import { useSettings } from '@/providers/settings-provider';
function SidebarController() {
const { getOption, storeOption } = useSettings();
// Get current sidebar state
const sidebarCollapsed = getOption('layouts.demo1.sidebarCollapse');
// Toggle sidebar state
const toggleSidebar = () => {
storeOption('layouts.demo1.sidebarCollapse', !sidebarCollapsed);
};
return (
);
}
```
--------------------------------
### GitHub Actions Workflow for Vercel Deployment
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
This GitHub Actions workflow automates the deployment of a Next.js site to Vercel. It checks out the code, sets up Node.js, installs the Vercel CLI, and deploys to production.
```yaml
name: Deploy Next.js site to Vercel
on:
push:
branches: ["main"]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18
- name: Install Vercel CLI
run: npm install --global vercel@latest
- name: Deploy to Vercel
run: vercel deploy --prod --token=${{ secrets.VERCEL_TOKEN }}
```
--------------------------------
### Tooltip Component Usage
Source: https://docs.keenthemes.com/metronic-nextjs/guides/providers
Provides an example of creating a button with a tooltip using the `Tooltip`, `TooltipContent`, and `TooltipTrigger` components. This relies on the `TooltipsProvider` being active.
```typescript
'use client';
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip';
function ButtonWithTooltip() {
return (
Tooltip content
);
}
```
--------------------------------
### Create Custom Image Optimization Loader
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
Create a custom image loader file (`my-image-loader.js`) to define how Next.js optimizes images. This example uses a CDN.
```javascript
// my-image-loader.js
export default function myImageLoader({ src, width, quality }) {
return `https://your-cdn.com/${src}?w=${width}&q=${quality || 75}`
}
```
--------------------------------
### Navigate Between Routes
Source: https://docs.keenthemes.com/metronic-nextjs/guides/routing
Examples of using the Link component for standard navigation and programmatic navigation via hooks.
```tsx
import Link from 'next/link';
// Basic link
Dashboard
// Link with additional props
Profile
```
```tsx
'use client';
import { useRouter } from 'next/navigation';
function LoginForm() {
const router = useRouter();
const handleSubmit = async (e) => {
e.preventDefault();
// Login logic...
router.push('/dashboard');
};
return ;
}
```
--------------------------------
### Nginx Configuration for Reverse Proxy
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
Example Nginx configuration when deploying behind a reverse proxy. Ensure the `proxy_pass` directive points to your running Next.js application.
```nginx
location /my-app {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
```
--------------------------------
### Settings Provider for Local Storage Persistence
Source: https://docs.keenthemes.com/metronic-nextjs/guides/providers
Illustrates how to use the `useSettings` hook to get and store application settings, with automatic persistence to localStorage. Ensure the `SettingsProvider` is included in your layout.
```typescript
'use client';
import { useSettings } from '@/providers/settings-provider';
function LayoutSettings() {
const { getOption, storeOption } = useSettings();
const sidebarCollapsed = getOption('layouts.demo1.sidebarCollapse');
function toggleSidebar() {
storeOption('layouts.demo1.sidebarCollapse', !sidebarCollapsed);
}
return ;
}
```
--------------------------------
### Translation with Variables
Source: https://docs.keenthemes.com/metronic-nextjs/guides/internationalization
Pass variables to translation strings to dynamically insert values. The example assumes a translation key like `greeting` with the format `Hello, {{name}}!`.
```javascript
// Translation: "Hello, {{name}}!"
const greeting = t('greeting', { name: 'John' });
```
--------------------------------
### Clean Up Environment Variables
Source: https://docs.keenthemes.com/metronic-nextjs/guides/custom-auth
Remove or comment out NextAuth and database-related environment variables from your `.env.local` file to reflect the removal of NextAuth and potentially a different database setup.
```dotenv
# Remove these NextAuth variables:
# NEXTAUTH_URL=
# NEXTAUTH_SECRET=
# GOOGLE_CLIENT_ID=
# GOOGLE_CLIENT_SECRET=
# Remove these database variables:
# DATABASE_URL=
# DIRECT_URL=
```
--------------------------------
### Configure Environment Variable
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/supabase
Add the database connection string to the project's .env file.
```text
DATABASE_URL=postgres://username:password@db.supabase.co:5432/dbname
```
--------------------------------
### Configure Environment Variables
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/installation
Define necessary credentials for database, authentication, storage, and SMTP services.
```text
# Prisma Config #
# Connect to Supabase via connection pooling.
DATABASE_URL="postgresql://postgres.your-project:your-password@aws-0-region.pooler.supabase.com:6543/postgres?pgbouncer=true"
# Direct connection to the database. Used for migrations.
DIRECT_URL="postgresql://postgres.your-project:your-password@aws-0-region.pooler.supabase.com:5432/postgres"
# Next Auth Config #
NEXT_PUBLIC_API_URL=http://localhost:3000/api
NEXTAUTH_URL=http://localhost:3000/
NEXTAUTH_SECRET=your-nextauth-secret-key
GOOGLE_CLIENT_ID=your_google_oauth2_client_id
GOOGLE_CLIENT_SECRET=your_google_oauth2_secret_key
# Storage Configuration (AWS S3 or DigitalOcean Spaces)
STORAGE_TYPE=digitalocean
STORAGE_ACCESS_KEY_ID=your_accent_key_id
STORAGE_SECRET_ACCESS_KEY=your_access_key
STORAGE_REGION=your_region
STORAGE_BUCKET=your_bucket_name
STORAGE_ENDPOINT=your_endpoint
STORAGE_FORCE_PATH_STYLE=true
STORAGE_CDN_URL=your_cdn_url
# SMTP Credentials
SMTP_HOST=your_smtp_host
SMTP_PORT=your_smtp_port
SMTP_SECURE=false
SMTP_USER=no-reply@domain.com
SMTP_PASS=your_smtp_pass
# Base Path (Optional - for subdirectory deployments)
# Set this if deploying to a subdirectory like /my-app
# NEXT_PUBLIC_BASE_PATH=/my-app
```
--------------------------------
### Organize Routes with Route Groups
Source: https://docs.keenthemes.com/metronic-nextjs/guides/routing
Demonstrates how folders with parentheses group routes without affecting the URL path.
```text
app/
├── (auth)/ # Authentication routes that don't include "(auth)" in URL
│ ├── signin/ # URL: /signin
│ └── signup/ # URL: /signup
└── (protected)/ # Protected routes that don't include "(protected)" in URL
└── account/ # URL: /account
```
--------------------------------
### Configure Prisma Database URL
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/prisma
Add the connection string to your .env file to allow Prisma to connect to the database.
```text
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=your_api_key"
```
```text
DATABASE_URL="prisma+postgres://username:password@host:port/database?api_key=your_api_key"
```
--------------------------------
### Configure Base Path using Environment Variable
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
Recommended method for subdirectory deployment. Set the `NEXT_PUBLIC_BASE_PATH` environment variable in your `.env.production` file.
```env
# For subdirectory deployment
NEXT_PUBLIC_BASE_PATH=/
```
--------------------------------
### Deploy Prisma Schema
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/supabase
Command to apply changes from the prisma/schema.prisma file to the database.
```bash
npx prisma db push
```
--------------------------------
### Implement theme patterns with Server Components
Source: https://docs.keenthemes.com/metronic-nextjs/guides/dark-mode
Demonstrates the integration of server-rendered content with client-side theme toggling.
```typescript
// app/theme-example/page.tsx
import { ServerThemeContent } from './server-content';
import { ClientThemeToggle } from './client-toggle';
// This is a server component
export default function ThemePage() {
return (
Theme Example Page
{/* This content uses dark mode classes but doesn't need theme state */}
{/* Client component boundary for theme toggling */}
);
}
```
```typescript
// app/theme-example/server-content.tsx
// This is a server component that uses dark mode classes
export function ServerThemeContent() {
return (
This component is rendered on the server, but still responds to theme
changes thanks to Tailwind's dark mode classes.
);
}
```
--------------------------------
### Environment Configuration
Source: https://docs.keenthemes.com/metronic-nextjs/guides/authentication
Required environment variables for NextAuth and OAuth providers.
```text
# NextAuth Configuration
NEXTAUTH_URL=http://localhost:3000/
NEXTAUTH_SECRET=your-nextauth-secret-key
# OAuth Providers
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
```
--------------------------------
### Implement Credentials Login Form
Source: https://docs.keenthemes.com/metronic-nextjs/guides/authentication
Uses NextAuth.js signIn method to authenticate users via email and password. Requires 'use client' directive and state management for form inputs.
```javascript
'use client';
import { useState } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter } from 'next/navigation';
export default function LoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const router = useRouter();
async function handleSubmit(e) {
e.preventDefault();
setError('');
const result = await signIn('credentials', {
redirect: false,
email,
password,
});
if (result?.error) {
setError(result.error);
} else {
router.push('/');
}
}
return (
);
}
```
--------------------------------
### TanStack Query Usage for Data Fetching
Source: https://docs.keenthemes.com/metronic-nextjs/guides/providers
Demonstrates how to use the `useQuery` hook from TanStack Query for fetching and caching user data. Ensure the `QueryProvider` is set up in your layout.
```typescript
'use client';
import { useQuery } from '@tanstack/react-query';
function UserProfile({ userId }: { userId: string }) {
const { data, isLoading, error } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetch(`/api/users/${userId}`).then(res => res.json())
});
if (isLoading) return
Loading...
;
if (error) return
Error loading user
;
return
{data.name}
{data.email}
;
}
```
--------------------------------
### Authentication System File Structure
Source: https://docs.keenthemes.com/metronic-nextjs/guides/authentication
Overview of the directory layout for the authentication system within the Metronic Next.js project.
```text
app/
├── (auth)/ # Authentication routes
│ ├── signin/ # Sign in page
│ ├── signup/ # Sign up page
│ └── reset-password/ # Password reset page
├── api/
│ └── auth/
│ └── [...nextauth]/ # NextAuth API routes
│ ├── auth-options.ts # NextAuth configuration
│ └── route.ts # API route handler
├── components/
│ └── ui/ # UI components for forms
prisma/
└── schema.prisma # Database schema with User model
providers/
└── auth-provider.tsx # NextAuth SessionProvider
```
--------------------------------
### View Layout Component Structure
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/starter-kits
Shows the file organization within a specific layout directory.
```text
components/layouts/layout-1/
├── components/
│ ├── header.tsx # Main header
│ ├── sidebar.tsx # Sidebar navigation
│ ├── sidebar-menu.tsx # Menu items
│ ├── sidebar-header.tsx # Sidebar header
│ ├── toolbar.tsx # Page toolbar
│ ├── breadcrumb.tsx # Breadcrumb navigation
│ ├── mega-menu.tsx # Mega menu
│ ├── mega-menu-mobile.tsx # Mobile menu
│ ├── footer.tsx # Footer
│ ├── main.tsx # Main content area
│ └── context.tsx # Layout context
├── shared/ # Shared components
└── index.tsx # Layout entry point
```
--------------------------------
### Clear Build Cache
Source: https://docs.keenthemes.com/metronic-nextjs/getting-started/installation
Run these commands to resolve build errors by removing existing build artifacts and reinstalling dependencies.
```bash
rm -rf node_modules .next
npm install --force
```
--------------------------------
### Loading UI Component
Source: https://docs.keenthemes.com/metronic-nextjs/guides/routing
Implement a `loading.tsx` file to define a custom loading UI that displays while content is being fetched.
```javascript
export default function Loading() {
return
Loading...
;
}
```
--------------------------------
### Create Simple Auth Context
Source: https://docs.keenthemes.com/metronic-nextjs/guides/custom-auth
Provides a React context for managing authentication state, including user data, login/logout functions, and loading status. It uses localStorage for session persistence and includes mock authentication logic. Use this provider at the root of your application to enable authentication features.
```typescript
'use client';
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
interface User {
id: string;
email: string;
name: string;
avatar?: string;
}
interface AuthContextType {
user: User | null;
login: (email: string, password: string) => Promise;
logout: () => void;
isLoading: boolean;
// Keep these for compatibility with existing UI
data: { user: User | null } | null;
status: 'loading' | 'authenticated' | 'unauthenticated';
}
const AuthContext = createContext(undefined);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
// Check for existing session on mount
useEffect(() => {
const savedUser = localStorage.getItem('auth-user');
if (savedUser) {
setUser(JSON.parse(savedUser));
}
setIsLoading(false);
}, []);
const login = async (email: string, password: string): Promise => {
setIsLoading(true);
// Mock authentication - replace with your API call
await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate API delay
if (email === 'demo@kt.com' && password === 'demo123') {
const mockUser: User = {
id: '1',
email: 'demo@kt.com',
name: 'Demo User',
avatar: '/media/avatars/300-2.png'
};
setUser(mockUser);
localStorage.setItem('auth-user', JSON.stringify(mockUser));
setIsLoading(false);
return true;
}
setIsLoading(false);
return false;
};
const logout = () => {
setUser(null);
localStorage.removeItem('auth-user');
};
// Compatibility properties for existing UI components
const data = user ? { user } : null;
const status = isLoading ? 'loading' : user ? 'authenticated' : 'unauthenticated';
return (
{children}
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
// For compatibility with NextAuth useSession hook
export function useSession() {
const { data, status } = useAuth();
return { data, status };
}
// Mock signIn function for compatibility
export async function signIn(provider: string, options?: Record) {
// Suppress unused parameter warning
void options;
if (provider === 'credentials') {
// This will be handled by your login form
return { error: null };
}
if (provider === 'google') {
// Mock Google sign in - replace with your implementation
console.log('Google sign in clicked - implement your Google auth here');
return { error: null };
}
return { error: 'Provider not supported' };
}
// Mock signOut function for compatibility
export function signOut() {
// For compatibility, we'll handle logout through the context directly
const authUser = localStorage.getItem('auth-user');
if (authUser) {
localStorage.removeItem('auth-user');
window.location.reload(); // Force a reload to update the auth state
}
}
```
--------------------------------
### Define Dynamic Route Structure
Source: https://docs.keenthemes.com/metronic-nextjs/guides/adding-new-page
Folder structure for implementing dynamic parameters in the App Router.
```text
app/
└── (protected)/
└── reports/
└── [id]/
└── page.tsx
```
--------------------------------
### Hardcode Base Path in next.config.mjs
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
Alternatively, hardcode the `basePath` and `assetPrefix` directly in your `next.config.mjs` file for subdirectory deployments.
```javascript
const nextConfig = {
basePath: '/your-custom-path',
assetPrefix: '/your-custom-path',
output: 'standalone',
};
```
--------------------------------
### NextAuth.js Session Management
Source: https://docs.keenthemes.com/metronic-nextjs/guides/providers
Shows how to use the `useSession`, `signIn`, and `signOut` functions from next-auth/react to manage user authentication state. This requires the `AuthProvider` to be active.
```typescript
'use client';
import { useSession, signIn, signOut } from 'next-auth/react';
function LoginButton() {
const { data: session } = useSession();
if (session) {
return ;
}
return ;
}
```
--------------------------------
### Create a Client-Side Interactive Page
Source: https://docs.keenthemes.com/metronic-nextjs/guides/routing
Requires the 'use client' directive to enable React hooks and browser-side interactivity.
```tsx
'use client';
import { useState } from 'react';
export default function SettingsPage() {
const [saved, setSaved] = useState(false);
return (
Settings
{saved &&
Settings saved!
}
);
}
```
--------------------------------
### Implement Clipboard Functionality with useCopyToClipboard
Source: https://docs.keenthemes.com/metronic-nextjs/guides/hooks
Use `useCopyToClipboard` to easily add copy-to-clipboard functionality to your components. It manages the copied state and includes an optional reset timeout. Import from '@/hooks/use-copy-to-clipboard'.
```javascript
'use client';
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard';
function CopyableText({ text }: { text: string }) {
const { isCopied, copyToClipboard } = useCopyToClipboard({
timeout: 2000 // Reset after 2 seconds
});
return (
{text}
);
}
```
--------------------------------
### Theme Provider for Dark/Light Mode
Source: https://docs.keenthemes.com/metronic-nextjs/guides/providers
Demonstrates toggling between dark and light modes using the `useTheme` hook from next-themes. This functionality is managed by the `ThemeProvider`.
```typescript
'use client';
import { useTheme } from 'next-themes';
function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
);
}
```
--------------------------------
### Create a Custom Layout Component
Source: https://docs.keenthemes.com/metronic-nextjs/guides/layouts
Define a reusable layout component with header, main, and footer sections.
```typescript
// app/components/layouts/custom/layout.tsx
export function CustomLayout({ children }) {
return (
My Custom Header{children}
);
}
```
--------------------------------
### App Router Layout Structure
Source: https://docs.keenthemes.com/metronic-nextjs/guides/layouts
Illustrates the directory structure for defining layouts in the Next.js App Router, showing how root, authentication, and protected layouts are organized.
```treeview
app/
├── layout.tsx # Root layout (applies to all routes)
├── (auth)/
│ └── layout.tsx # Auth layout (applies to all auth routes)
└── (protected)/
├── layout.tsx # Protected layout (applies to all protected routes)
└── account/
└── layout.tsx # Account layout (applies to all account routes)
```
--------------------------------
### Production Environment Variables
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
Configure production-specific environment variables in a `.env.production` file. Variables prefixed with `NEXT_PUBLIC_` are exposed to the browser.
```env
NEXT_PUBLIC_APP_NAME=metronic-nextjs
NEXT_PUBLIC_API_URL=https://your-production-api.com/api
NEXTAUTH_URL=https://your-domain.com
NEXTAUTH_SECRET=your-secret-key
```
--------------------------------
### Create Not Found Page
Source: https://docs.keenthemes.com/metronic-nextjs/guides/adding-new-page
UI component for handling 404 scenarios for specific routes.
```tsx
// app/(protected)/reports/[id]/not-found.tsx
export default function ReportNotFound() {
return (
Report Not Found
The report you're looking for doesn't exist.
);
}
```
--------------------------------
### Create a Basic Page Component
Source: https://docs.keenthemes.com/metronic-nextjs/guides/routing
Standard structure for a server-side rendered page component.
```tsx
// Basic page component
export default function AccountPage() {
return (
Account Settings
Manage your account preferences
);
}
```
--------------------------------
### Remove Prisma Client
Source: https://docs.keenthemes.com/metronic-nextjs/guides/custom-auth
Delete the prisma client configuration file.
```bash
rm -f lib/prisma.ts
```
--------------------------------
### Monitor Viewport Dimensions with useViewport
Source: https://docs.keenthemes.com/metronic-nextjs/guides/hooks
Use `useViewport` to track the browser window's height and width. It automatically updates when the window is resized. Import from '@/hooks/use-viewport'.
```javascript
'use client';
import { useViewport } from '@/hooks/use-viewport';
function ResponsiveComponent() {
const [height, width] = useViewport();
return (
Viewport Dimensions
Width: {width}px
Height: {height}px
);
}
```
--------------------------------
### Root Layout with Nested Providers
Source: https://docs.keenthemes.com/metronic-nextjs/guides/providers
This code sets up the nested structure of context providers in the root layout, providing access to various application states and functionalities for all components.
```typescript
import { AuthProvider } from '@/providers/auth-provider';
import { I18nProvider } from '@/providers/i18n-provider';
import { QueryProvider } from '@/providers/query-provider';
import { SettingsProvider } from '@/providers/settings-provider';
import { ThemeProvider } from '@/providers/theme-provider';
import { TooltipsProvider } from '@/providers/tooltips-provider';
export default function RootLayout({
children,
}: { children: React.ReactNode }) {
return (
{children}
);
}
```
--------------------------------
### Update Menu Configuration
Source: https://docs.keenthemes.com/metronic-nextjs/guides/custom-auth
Comment out or remove the user management section in the menu configuration file.
```typescript
// Remove or comment out this section:
/*
{
title: 'User Management',
icon: ShieldUser,
children: [
{
title: 'Users',
path: '/user-management/users',
},
{
title: 'Roles',
path: '/user-management/roles',
},
// ... other user management menu items
],
},
*/
```
--------------------------------
### Protected Layout with Authentication Check
Source: https://docs.keenthemes.com/metronic-nextjs/guides/layouts
Implements a protected layout that uses `next-auth/react` to check user authentication status. Redirects unauthenticated users to the sign-in page and shows a loading state.
```javascript
'use client';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
export default function ProtectedLayout({ children }) {
const { status } = useSession();
const router = useRouter();
useEffect(() => {
if (status === 'unauthenticated') {
router.push('/signin');
}
}, [status, router]);
if (status === 'loading') {
return
Loading...
;
}
return status === 'authenticated' ? children : null;
}
```
--------------------------------
### I18n Provider for Language and RTL Support
Source: https://docs.keenthemes.com/metronic-nextjs/guides/providers
Shows how to manage language selection and RTL support using the `useLanguage` hook and `I18N_LANGUAGES` from the i18n configuration. Requires the `I18nProvider`.
```typescript
'use client';
import { useLanguage } from '@/providers/i18n-provider';
import { I18N_LANGUAGES } from '@/i18n/config';
function LanguageSelector() {
const { languageCode, changeLanguage } = useLanguage();
return (
);
}
```
--------------------------------
### Accessing Catch-all Route Parameters
Source: https://docs.keenthemes.com/metronic-nextjs/guides/routing
Catch-all parameters are provided as an array in the `params` prop, allowing you to join them into a single string.
```javascript
export default function DocsPage({ params }) {
// slug will be an array, e.g., ['a', 'b', 'c'] for /docs/a/b/c
return
Slug segments: {params.slug.join('/')}
;
}
```
--------------------------------
### Set Base Path for Nginx Deployment
Source: https://docs.keenthemes.com/metronic-nextjs/guides/deployment
After configuring Nginx, set the `NEXT_PUBLIC_BASE_PATH` environment variable in your `.env.production` file to match the Nginx location.
```env
NEXT_PUBLIC_BASE_PATH=/my-app
```
--------------------------------
### Create a forced theme wrapper component
Source: https://docs.keenthemes.com/metronic-nextjs/guides/dark-mode
Use this wrapper to ensure specific UI elements maintain a consistent theme regardless of the global site setting.
```typescript
// components/always-light-theme.tsx
'use client';
import { ThemeProvider } from 'next-themes';
import { ReactNode } from 'react';
export function AlwaysLightTheme({ children }: { children: ReactNode }) {
return (
{children}
);
}
```
--------------------------------
### Create Simplified User Model
Source: https://docs.keenthemes.com/metronic-nextjs/guides/custom-auth
Define a simplified `User` interface and mock data for UI display purposes. This version removes complex properties like roles, status, and timestamps.
```typescript
// Simple user types for UI display only
export interface User {
id: string;
email: string;
name: string;
avatar?: string;
}
// Mock data for development
export const MOCK_USER: User = {
id: '1',
email: 'demo@kt.com',
name: 'Demo User',
avatar: '/media/avatars/300-2.png'
};
```
--------------------------------
### Manage Navigation Menu State with useMenu
Source: https://docs.keenthemes.com/metronic-nextjs/guides/hooks
The `useMenu` hook helps manage the open/closed state and active status for navigation menus, including nested structures. Import from '@/hooks/use-menu'.
```javascript
'use client';
import { useMenu } from '@/hooks/use-menu';
function NavigationMenu() {
const { isActive, toggle, close } = useMenu();
// Example menu items
const menuItems = [
{ title: 'Dashboard', path: '/dashboard' },
{
title: 'Users',
path: '/users',
children: [
{ title: 'User List', path: '/users/list' },
{ title: 'User Profile', path: '/users/profile' }
]
}
];
return (