typescriptbeginner
Server-Only Utility Functions
Ensure utility functions only run on the server using the server-only package to prevent client leakage.
typescriptPress ⌘/Ctrl + Shift + C to copy
// lib/server-utils.ts
import 'server-only';
export async function getSecretConfig() {
return {
dbUrl: process.env.DATABASE_URL!,
apiKey: process.env.API_SECRET_KEY!,
jwtSecret: process.env.JWT_SECRET!,
};
}
export async function hashPassword(password: string): Promise<string> {
const { createHash } = await import('crypto');
return createHash('sha256').update(password).digest('hex');
}
export async function verifyToken(token: string) {
const config = await getSecretConfig();
// Verify JWT token server-side only
return { valid: true, userId: '123' };
}
// If a client component tries to import this file,
// it will throw a build error:
// "This module cannot be imported from a Client Component module."
// Usage in a Server Component:
// import { getSecretConfig } from '@/lib/server-utils';Use Cases
- protecting secrets
- server-only logic
- preventing client leakage
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
Next.js Middleware for Authentication
Protect routes with Next.js middleware using token verification and role-based redirects.
Best for: Protecting authenticated routes at the edge
#nextjs#middleware
typescriptintermediate
API Route Rate Limiting
Add rate limiting to Next.js API routes with sliding window, IP-based limits, and custom responses.
Best for: API abuse prevention
#nextjs#api
typescriptintermediate
Parallel Data Fetching in Server Components
Fetch multiple data sources in parallel using Promise.all in Next.js server components for faster page loads.
Best for: dashboard pages
#nextjs#data-fetching
typescriptintermediate
Search Params in Server and Client Components
Handle URL search params in both server and client components with type-safe parsing.
Best for: product filters
#nextjs#search-params