Next.js course ยท Module 5: Rendering Strategies
Edge Runtime and Performance Optimization
In this lesson8
In the world of modern web applications, performance is a key factor affecting user experience and business success. Next.js offers advanced tools for performance optimization, among which Edge Runtime stands out as a powerful solution. In this module, we will discuss Edge Runtime and other performance optimization strategies in Next.js applications.
Edge Runtime in Next.js
What Is Edge Runtime?
Edge Runtime is a lightweight execution environment that enables running code closer to the end user - on the "edge" of the network - instead of in a central data center. Next.js enables running Route Handlers and pages in Edge Runtime, which provides:
- Lower latency - code executes closer to the user
- Faster Time to First Byte (TTFB) - faster response delivery
- Global scaling - automatic distribution worldwide
- Lower memory usage - thanks to the lighter runtime
Differences Between Edge Runtime and Node.js Runtime
It's worth understanding the differences between Edge Runtime and the traditional Node.js environment:
| Feature | Edge Runtime | Node.js Runtime |
|---|---|---|
| Cold start time | Very fast (milliseconds) | Slower (hundreds of milliseconds) |
| Scalability | Automatic, global | Requires configuration |
| API access | Limited set | Full Node.js API |
| Code size | Limited (typically 1-4 MB) | Practically unlimited |
| File system access | None | Full access |
| Function execution time | Limited (e.g., 50-60 ms) | Longer (minutes) |
| Typical use cases | APIs, pages with dynamic content | Complex operations, database access |
Configuring Edge Runtime in Next.js
To run a page component or Route Handler in Edge Runtime, we use the runtime export in the file:
// app/api/edge-route/route.ts
import { NextRequest } from 'next/server';
export const runtime = 'edge'; // Edge Runtime declaration
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const query = searchParams.get('query') || 'World';
// Handling the request with minimal latency
return Response.json({ message: `Hello, ${query}!` });
}For a page or Layout component:
// app/edge-page/page.tsx
import { cookies } from 'next/headers';
export const runtime = 'edge';
export default async function EdgePage() {
const cookie = (await cookies()).get('theme')?.value || 'light';
return (
<div>
<h1>Page Rendered in Edge Runtime</h1>
<p>Your theme: {cookie}</p>
</div>
);
}When to Use Edge Runtime?
Edge Runtime is ideal for:
- Dynamic personalization - e.g., geolocation, user preferences
- API proxy - forwarding requests to other services with minimal latency
- A/B testing - quick decisions about which version to display
- Simple dynamic pages - that don't require complex operations
- International audiences - when network latency matters
Geolocation example in Edge Runtime:
// app/edge-geo/page.tsx
import { headers } from 'next/headers';
export const runtime = 'edge';
export default async function GeoPage() {
const headersList = await headers();
const countryCode = headersList.get('x-vercel-ip-country') || 'Unknown';
const city = headersList.get('x-vercel-ip-city') || 'Unknown City';
return (
<div>
<h1>Welcome, visitor!</h1>
<p>We detected you are from: {city}, {countryCode}</p>
{countryCode === 'PL' && (
<p>Special content for visitors from Poland!</p>
)}
</div>
);
}Image and Media Optimization
Next.js offers built-in solutions for media optimization that significantly impact application performance.
Next.js Image Component
The Image component in Next.js automatically optimizes images, reducing the size of transmitted data and improving Web Vitals metrics:
import Image from 'next/image';
export default function OptimizedImages() {
return (
<div>
<h2>Optimized Images in Next.js</h2>
<Image
src="/hero-image.jpg" // Relative path in the public directory
alt="Hero Image"
width={1200}
height={600}
priority // Loading priority for above-the-fold images
/>
<Image
src="https://cdn.example.com/remote-image.jpg" // Remote image
alt="Remote Image"
width={800}
height={400}
quality={80} // Quality adjustment (1-100)
placeholder="blur"
blurDataURL="data:image/svg+xml;base64,..." // Optional placeholder while loading
/>
</div>
);
}Key features of the Image component:
- Automatic responsive sizes - generating different image sizes
- Lazy loading - images loaded only when visible
- Conversion to modern formats - WebP, AVIF
- Quality optimization - file size reduction while maintaining quality
- Loading placeholder - blur effect preventing layout shifts (CLS)
Font Optimization
Next.js App Router introduces a new font loading system that eliminates text flickering issues (CLS):
// app/layout.tsx
import { Inter, Roboto_Mono } from 'next/font/google';
// Variable font configuration
const inter = Inter({
subsets: ['latin', 'latin-ext'],
display: 'swap',
});
// Fixed-weight font configuration
const robotoMono = Roboto_Mono({
subsets: ['latin'],
display: 'swap',
weight: ['400', '700'],
});
export default function RootLayout({ children }) {
return (
<html lang="en" className={`${inter.className} ${robotoMono.variable}`}>
<body>{children}</body>
</html>
);
}In a component, we can use the defined font:
// app/page.tsx
export default function Home() {
return (
<main>
<h1 className={inter.className}>Heading in Inter Font</h1>
<code className="font-mono">// This will be in Roboto Mono thanks to the CSS variable</code>
</main>
);
}Data Optimization Strategies
React Server Components and Bundle Size Reduction
React Server Components (RSC) allow significantly reducing the amount of JavaScript sent to the browser:
// app/products/page.tsx - Server Component (default)
async function getProducts() {
const res = await fetch('https://api.example.com/products');
return res.json();
}
export default async function ProductsPage() {
// This code is NEVER sent to the client
const products = await getProducts();
const totalValue = products.reduce((sum, product) => sum + product.price, 0);
return (
<div>
<h1>Products (value: ${totalValue})</h1>
<ProductList products={products} />
</div>
);
}Streaming and Suspense
Streaming enables progressive UI delivery, which speeds up Time to First Byte and improves interactivity:
// app/dashboard/page.tsx
import { Suspense } from 'react';
import Loading from './loading';
// Components loading data independently from each other
import UserProfile from './UserProfile';
import RecentOrders from './RecentOrders';
import Analytics from './Analytics';
export default function Dashboard() {
return (
<div className="dashboard">
<h1>Control Panel</h1>
<div className="dashboard-grid">
{/* Faster-loading elements will be visible immediately */}
<Suspense fallback={<Loading section="profile" />}>
<UserProfile />
</Suspense>
<Suspense fallback={<Loading section="orders" />}>
<RecentOrders />
</Suspense>
<Suspense fallback={<Loading section="analytics" />}>
<Analytics />
</Suspense>
</div>
</div>
);
}Routing and Navigation Optimization
Prefetching and Parallel Routes
Next.js App Router automatically prefetches links visible in the viewport, which can be further controlled:
import Link from 'next/link';
export default function Navigation() {
return (
<nav>
{/* Default prefetch */}
<Link href="/products">Products</Link>
{/* Disabled prefetch */}
<Link href="/heavy-page" prefetch={false}>Heavy Page</Link>
{/* Prefetch headers only (for dynamic pages) */}
<Link href="/blog/article-123">Article</Link>
</nav>
);
}Parallel Routes enable loading multiple page sections independently from each other:
// app/layout.tsx
export default function Layout({ children, sidebar }) {
return (
<div className="layout">
<aside className="sidebar">
{sidebar}
</aside>
<main>
{children}
</main>
</div>
);
}
// app/@sidebar/page.tsx - loaded independently
export default function Sidebar() {
return <div>Sidebar Content</div>;
}
// app/page.tsx - main content
export default function Home() {
return <div>Main Content</div>;
}Route Handlers and API Optimization
Route Handlers can be optimized for performance, especially when combined with Edge Runtime:
// app/api/optimized/route.ts
import { NextResponse } from 'next/server';
export const runtime = 'edge';
export async function GET() {
// Applying CORS for preflight optimization
const response = NextResponse.json({ data: 'value' });
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type');
// Setting Cache-Control for the browser
response.headers.set(
'Cache-Control',
'public, max-age=60, s-maxage=3600, stale-while-revalidate=600'
);
return response;
}Advanced Optimization Techniques
Best Practices for generateStaticParams
The generateStaticParams function is used to generate static versions of pages with parameters:
// app/products/[category]/[id]/page.tsx
export async function generateStaticParams() {
// Fetch only the necessary data for path generation
const categories = await fetch('https://api.example.com/categories').then(r => r.json());
// Generate parameter combinations for the most important pages
const paths = [];
for (const category of categories) {
// Fetch only top products for each category
const topProducts = await fetch(
`https://api.example.com/categories/${category.id}/top-products`
).then(r => r.json());
for (const product of topProducts) {
paths.push({
category: category.slug,
id: product.id.toString(),
});
}
}
return paths;
}
export default async function ProductPage({ params }) {
const { category, id } = await params;
// Product page...
}Optimization involves:
- Generating only the most important parameters (e.g., most popular products)
- Minimizing the number of queries during building
- Properly caching data used for parameter generation
CSS and Style Optimization
Next.js supports various CSS loading strategies that can be optimized:
// app/products/[id]/page.tsx
import './product-page.css'; // Global CSS for this route
// CSS Modules for the component
import styles from './ProductDetails.module.css';
// Styled JSX (built-in option)
function ProductColorChoice() {
return (
<div className="color-selector">
<style jsx>{`
.color-selector {
display: flex;
gap: 8px;
}
.color-option {
width: 24px;
height: 24px;
border-radius: 50%;
cursor: pointer;
}
`}</style>
<div className="color-option" style={{ backgroundColor: 'red' }} />
<div className="color-option" style={{ backgroundColor: 'blue' }} />
</div>
);
}
export default async function ProductPage({ params }) {
return (
<div className={styles.productContainer}>
<h1 className={styles.productTitle}>Product Details {(await params).id}</h1>
<ProductColorChoice />
</div>
);
}CSS optimization:
- CSS Modules for component style isolation
- Automatic removal of unused CSS (tree-shaking)
- Grouping CSS into chunks according to application routes
Leveraging HTTP/2 and HTTP/3
Hosting Next.js on platforms supporting modern HTTP/2 and HTTP/3 protocols provides better performance through:
- Request multiplexing - multiple requests through a single connection
- Header compression - lower communication overhead
- Server Push - the server can send resources before the client requests them
This doesn't require code changes, just appropriate server configuration or choosing a hosting platform (e.g., Vercel, Netlify, Cloudflare Pages).
Performance Analysis and Improvement Tools
Next.js Analytics and Web Vitals
Next.js offers built-in Web Vitals metrics that we can track:
// instrumentation.ts (in the root directory)
export function register() {
if (typeof window !== 'undefined') {
// This solution works only on the client side
import('web-vitals').then(({ onCLS, onFID, onLCP, onTTFB }) => {
onCLS(metric => sendAnalyticsEvent('CLS', metric));
onFID(metric => sendAnalyticsEvent('FID', metric));
onLCP(metric => sendAnalyticsEvent('LCP', metric));
onTTFB(metric => sendAnalyticsEvent('TTFB', metric));
});
}
}
function sendAnalyticsEvent(name, metric) {
const body = JSON.stringify({
name,
value: metric.value,
page: window.location.pathname,
id: metric.id,
});
// Send to your own API
navigator.sendBeacon('/api/analytics', body);
}Bundle Size Audit and Analysis
Bundle size analysis is critical for performance. Next.js offers built-in bundle analysis:
next build --analyzeWe can also use more advanced tools like @next/bundle-analyzer:
// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({
// Next.js configuration
});Then we run:
ANALYZE=true npm run buildSecurity Best Practices in Next.js
In the Quantum Metropolis of 2150, security is not optional - it's a necessity. Every vulnerability in the system can be exploited by cybercriminals or hostile corporations. In this section, we will discuss the most important practices for securing Next.js applications that protect both user data and the integrity of the entire system.
CSRF Protection (Cross-Site Request Forgery)
CSRF is an attack where a malicious website uses an authenticated user's session to perform unauthorized actions. Next.js offers built-in protection mechanisms, especially in Server Actions.
Implementing CSRF Protection
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Verify the Origin header for mutations
if (request.method !== 'GET' && request.method !== 'HEAD') {
const origin = request.headers.get('origin');
const host = request.headers.get('host');
// Check if Origin matches the host
if (origin && !origin.includes(host || '')) {
return new NextResponse('Forbidden', { status: 403 });
}
}
return NextResponse.next();
}
export const config = {
matcher: '/api/:path*'
};CSRF Token for Forms
// lib/csrf.ts
import { cookies } from 'next/headers';
import crypto from 'crypto';
export async function generateCSRFToken(): Promise<string> {
const token = crypto.randomBytes(32).toString('hex');
const cookieStore = await cookies();
cookieStore.set('csrf-token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 60 * 60 // 1 hour
});
return token;
}
export async function verifyCSRFToken(token: string): Promise<boolean> {
const cookieStore = await cookies();
const storedToken = cookieStore.get('csrf-token')?.value;
return storedToken === token;
}
// app/actions.ts
'use server';
import { verifyCSRFToken } from '@/lib/csrf';
export async function submitForm(formData: FormData) {
const csrfToken = formData.get('csrf-token') as string;
if (!await verifyCSRFToken(csrfToken)) {
throw new Error('Invalid CSRF token');
}
// Process the form...
}
// app/my-form/page.tsx
import { generateCSRFToken } from '@/lib/csrf';
import { submitForm } from '@/app/actions';
export default async function MyFormPage() {
const csrfToken = await generateCSRFToken();
return (
<form action={submitForm}>
<input type="hidden" name="csrf-token" value={csrfToken} />
{/* Remaining form fields */}
<button type="submit">Submit</button>
</form>
);
}XSS Prevention (Cross-Site Scripting)
XSS is an attack where an attacker injects malicious JavaScript code into the application. Next.js and React offer built-in protection, but it's worth knowing additional techniques.
Default React Protection
React automatically escapes all values rendered in JSX:
// Safe - React automatically escapes
function UserProfile({ username }: { username: string }) {
// Even if username = "<script>alert('xss')</script>"
// React will display it as text, not execute it
return <div>Welcome, {username}!</div>;
}Be Careful with dangerouslySetInnerHTML
// DANGEROUS - can execute malicious code
function DangerousComponent({ html }: { html: string }) {
return <div dangerouslySetInnerHTML={{ __html: html }} />;
}
// SAFE - use a sanitization library
import DOMPurify from 'isomorphic-dompurify';
function SafeComponent({ html }: { html: string }) {
const sanitized = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['p', 'strong', 'em', 'a', 'ul', 'ol', 'li'],
ALLOWED_ATTR: ['href', 'target']
});
return <div dangerouslySetInnerHTML={{ __html: sanitized }} />;
}Content Security Policy (CSP)
CSP is a security mechanism against XSS that specifies which code sources are trusted:
// next.config.js
const ContentSecurityPolicy = `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline' https://trusted-cdn.com;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
img-src 'self' data: https: blob:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://api.example.com;
frame-ancestors 'none';
`;
const securityHeaders = [
{
key: 'Content-Security-Policy',
value: ContentSecurityPolicy.replace(/\s{2,}/g, ' ').trim()
}
];
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: securityHeaders
}
];
}
};Or via middleware:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
const csp = [
"default-src 'self'",
"script-src 'self' 'unsafe-eval' 'unsafe-inline'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"font-src 'self' data:",
"connect-src 'self' https://api.example.com"
].join('; ');
response.headers.set('Content-Security-Policy', csp);
return response;
}Rate Limiting - Protection Against Abuse
Rate limiting protects the application against DDoS attacks and API abuse. We can implement this in Next.js Middleware:
// lib/rate-limit.ts
import { LRUCache } from 'lru-cache';
type RateLimitOptions = {
interval: number; // time in milliseconds
uniqueTokenPerInterval: number; // maximum number of unique tokens
};
export function rateLimit(options: RateLimitOptions) {
const tokenCache = new LRUCache({
max: options.uniqueTokenPerInterval || 500,
ttl: options.interval || 60000
});
return {
check: (limit: number, token: string): { success: boolean; remaining: number } => {
const tokenCount = (tokenCache.get(token) as number[]) || [0];
if (tokenCount[0] === 0) {
tokenCache.set(token, [1]);
return { success: true, remaining: limit - 1 };
}
const currentCount = tokenCount[0];
if (currentCount >= limit) {
return { success: false, remaining: 0 };
}
tokenCache.set(token, [currentCount + 1]);
return { success: true, remaining: limit - currentCount - 1 };
}
};
}
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { rateLimit } from '@/lib/rate-limit';
const limiter = rateLimit({
interval: 60 * 1000, // 1 minute
uniqueTokenPerInterval: 500
});
export async function middleware(request: NextRequest) {
// Use IP as identifier
const ip = request.ip ?? 'anonymous';
try {
const { success, remaining } = limiter.check(10, ip); // 10 requests per minute
if (!success) {
return new NextResponse('Too Many Requests', {
status: 429,
headers: {
'X-RateLimit-Limit': '10',
'X-RateLimit-Remaining': '0',
'X-RateLimit-Reset': new Date(Date.now() + 60000).toISOString()
}
});
}
const response = NextResponse.next();
response.headers.set('X-RateLimit-Limit', '10');
response.headers.set('X-RateLimit-Remaining', remaining.toString());
return response;
} catch (error) {
return new NextResponse('Internal Server Error', { status: 500 });
}
}
export const config = {
matcher: '/api/:path*'
};Rate Limiting for Server Actions
// lib/rate-limit-server-action.ts
import { cookies } from 'next/headers';
const rateLimitStore = new Map<string, { count: number; resetAt: number }>();
export async function checkRateLimit(
action: string,
limit: number = 10,
windowMs: number = 60000
): Promise<boolean> {
const cookieStore = await cookies();
const sessionId = cookieStore.get('session-id')?.value || 'anonymous';
const key = `${sessionId}:${action}`;
const now = Date.now();
const record = rateLimitStore.get(key);
if (!record || now > record.resetAt) {
rateLimitStore.set(key, {
count: 1,
resetAt: now + windowMs
});
return true;
}
if (record.count >= limit) {
return false;
}
record.count++;
return true;
}
// app/actions.ts
'use server';
import { checkRateLimit } from '@/lib/rate-limit-server-action';
export async function sensitiveAction(data: FormData) {
const allowed = await checkRateLimit('sensitive-action', 5, 60000);
if (!allowed) {
throw new Error('Rate limit exceeded. Please try again later.');
}
// Execute the action...
}Secure Headers (HSTS, X-Frame-Options, etc.)
Proper HTTP headers are the foundation of web application security:
// next.config.js
const securityHeaders = [
{
key: 'X-DNS-Prefetch-Control',
value: 'on'
},
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload'
},
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN'
},
{
key: 'X-Content-Type-Options',
value: 'nosniff'
},
{
key: 'X-XSS-Protection',
value: '1; mode=block'
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin'
},
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=()'
}
];
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: securityHeaders
}
];
}
};Or via middleware for greater control:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
// HSTS - enforces HTTPS
response.headers.set(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains'
);
// X-Frame-Options - protection against clickjacking
response.headers.set('X-Frame-Options', 'SAMEORIGIN');
// X-Content-Type-Options - prevents MIME sniffing
response.headers.set('X-Content-Type-Options', 'nosniff');
// X-XSS-Protection - additional XSS protection
response.headers.set('X-XSS-Protection', '1; mode=block');
// Referrer-Policy - controls information in the Referer header
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
// Permissions-Policy - controls access to browser APIs
response.headers.set(
'Permissions-Policy',
'camera=(), microphone=(), geolocation=(), payment=()'
);
return response;
}API Routes and Server Actions Security
Input Validation in Server Actions
// app/actions.ts
'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
const CreatePostSchema = z.object({
title: z.string().min(3).max(100),
content: z.string().min(10).max(5000),
tags: z.array(z.string()).max(5).optional()
});
export async function createPost(formData: FormData) {
// Input data validation
const rawData = {
title: formData.get('title'),
content: formData.get('content'),
tags: formData.getAll('tags')
};
const validation = CreatePostSchema.safeParse(rawData);
if (!validation.success) {
return {
error: 'Validation failed',
issues: validation.error.issues
};
}
const { title, content, tags } = validation.data;
// Authentication verification
const session = await getServerSession();
if (!session?.user) {
return { error: 'Unauthorized' };
}
// HTML sanitization (if we allow formatting)
const sanitizedContent = sanitizeHtml(content);
try {
const post = await db.post.create({
data: {
title,
content: sanitizedContent,
tags,
authorId: session.user.id
}
});
revalidatePath('/blog');
return { success: true, post };
} catch (error) {
console.error('Failed to create post:', error);
return { error: 'Failed to create post' };
}
}Secure API Routes
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { z } from 'zod';
const QuerySchema = z.object({
page: z.coerce.number().min(1).default(1),
limit: z.coerce.number().min(1).max(100).default(10)
});
export async function GET(request: NextRequest) {
try {
// Authentication verification
const session = await getServerSession();
if (!session) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
// Query parameter validation
const { searchParams } = new URL(request.url);
const validation = QuerySchema.safeParse({
page: searchParams.get('page'),
limit: searchParams.get('limit')
});
if (!validation.success) {
return NextResponse.json(
{ error: 'Invalid parameters', issues: validation.error.issues },
{ status: 400 }
);
}
const { page, limit } = validation.data;
// Secure database query
const users = await db.user.findMany({
skip: (page - 1) * limit,
take: limit,
select: {
id: true,
name: true,
email: true,
// DO NOT return passwords or other sensitive data
}
});
return NextResponse.json({ users });
} catch (error) {
console.error('API Error:', error);
// DO NOT return error details in production
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}Additional Best Practices
1. Secure Secret Storage
// .env.local (NEVER commit to repo!)
DATABASE_URL="postgresql://..."
NEXTAUTH_SECRET="super-secret-key"
API_KEY="secret-api-key"
// app/config.ts
const requiredEnvVars = [
'DATABASE_URL',
'NEXTAUTH_SECRET',
'API_KEY'
] as const;
// Validate the presence of environment variables at startup
requiredEnvVars.forEach((varName) => {
if (!process.env[varName]) {
throw new Error(`Missing required environment variable: ${varName}`);
}
});
export const config = {
database: {
url: process.env.DATABASE_URL!
},
auth: {
secret: process.env.NEXTAUTH_SECRET!
},
api: {
key: process.env.API_KEY!
}
} as const;2. Secure Cookies
// lib/cookies.ts
import { cookies } from 'next/headers';
export async function setSecureCookie(name: string, value: string) {
const cookieStore = await cookies();
cookieStore.set(name, value, {
httpOnly: true, // Not accessible to JavaScript
secure: process.env.NODE_ENV === 'production', // HTTPS only in production
sameSite: 'strict', // CSRF protection
maxAge: 60 * 60 * 24 * 7, // 7 days
path: '/'
});
}3. Logging and Monitoring
// lib/logger.ts
export function logSecurityEvent(event: {
type: 'auth_failure' | 'rate_limit' | 'csrf_violation' | 'xss_attempt';
ip: string;
userAgent: string;
details?: any;
}) {
const logEntry = {
timestamp: new Date().toISOString(),
...event
};
// In production, send to a monitoring system (Sentry, LogRocket, etc.)
if (process.env.NODE_ENV === 'production') {
// sendToMonitoring(logEntry);
}
console.warn('Security Event:', logEntry);
}
// middleware.ts
export function middleware(request: NextRequest) {
const ip = request.ip ?? 'unknown';
const userAgent = request.headers.get('user-agent') ?? 'unknown';
// Log suspicious activities
if (isSuspicious(request)) {
logSecurityEvent({
type: 'csrf_violation',
ip,
userAgent,
details: { url: request.url }
});
}
return NextResponse.next();
}Security Best Practices Summary
In the Quantum Metropolis, security is a continuous process, not a one-time action. Key principles:
- Never trust user input - always validate and sanitize
- Use HTTPS everywhere - enforce through HSTS
- Implement rate limiting - protect against abuse
- Set secure headers - CSP, X-Frame-Options, etc.
- Protect against CSRF - verify Origin, use tokens
- Prevent XSS - sanitize HTML, use CSP
- Store secrets securely - use environment variables
- Log security events - monitor suspicious activities
- Regularly update dependencies - patch known vulnerabilities
- Apply the principle of least privilege - minimal permissions
Summary: Performance Optimization Best Practices
In summary, here are the key principles for performance optimization in Next.js:
- Use Edge Runtime for dynamic, global applications requiring low latency
- Leverage React Server Components to reduce the amount of JS sent to the client
- Optimize images using the
Imagecomponent from Next.js - Implement streaming with the
Suspensecomponent for better UI responsiveness - Manage caching at different levels (browser, CDN, server)
- Leverage prefetching for faster navigation between pages
- Monitor Web Vitals and continuously optimize critical rendering paths
- Optimize font loading using Next.js's built-in font system
- Eliminate unnecessary JavaScript through bundle size analysis and removing unused dependencies
- Test on real devices and slower connections to identify performance issues
By applying these practices, you can build Next.js applications that are both functional and blazingly fast, providing users with excellent experiences regardless of their location or device.
Code for this lesson: App.tsx
import React, { useState } from 'react';
// Edge Runtime and performance optimization in Next.js
interface RuntimeInfo {
name: string;
runtime: 'nodejs' | 'edge';
latency: number; // ms
coldStart: number; // ms
regions: string[];
features: string[];
}
const runtimes: RuntimeInfo[] = [
{
name: 'Node.js Runtime',
runtime: 'nodejs',
latency: 120,
coldStart: 250,
regions: ['us-east-1'],
features: ['Full Node.js API', 'fs, crypto, stream', 'No time limit', 'Large packages'],
},
{
name: 'Edge Runtime',
runtime: 'edge',
latency: 25,
coldStart: 5,
regions: ['Global CDN (30+ regions)'],
features: ['Web APIs', 'Fast cold start', 'Low latency', '25MB limit'],
},
];
function LatencyBar({ value, max, color }: { value: number; max: number; color: string }) {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div style={{ flex: 1, height: 12, background: '#1a2744', borderRadius: 6, overflow: 'hidden' }}>
<div style={{
width: `${(value / max) * 100}%`, height: '100%',
background: color, borderRadius: 6, transition: 'width 0.5s ease'
}} />
</div>
<span style={{ color, fontSize: 12, minWidth: 50 }}>{value}ms</span>
</div>
);
}
export default function EdgeRuntimeDemo() {
const [selected, setSelected] = useState<RuntimeInfo>(runtimes[1]);
const [pings, setPings] = useState<number[]>([]);
const simulatePing = () => {
const base = selected.runtime === 'edge' ? 15 : 80;
const jitter = Math.floor(Math.random() * 40);
setPings(prev => [...prev.slice(-11), base + jitter]);
};
const avg = pings.length > 0 ? Math.round(pings.reduce((a, b) => a + b, 0) / pings.length) : 0;
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: 20, color: '#e0e0e0', fontFamily: 'monospace' }}>
<h1 style={{ color: '#64ffda' }}>Edge Runtime and Performance</h1>
<div style={{ display: 'flex', gap: 12, margin: '16px 0' }}>
{runtimes.map(r => (
<button key={r.runtime} onClick={() => { setSelected(r); setPings([]); }} style={{
flex: 1, background: selected.runtime === r.runtime ? '#1565c0' : '#0d1117',
color: '#fff', border: `1px solid ${selected.runtime === r.runtime ? '#64ffda' : '#333'}`,
borderRadius: 8, padding: 16, cursor: 'pointer', fontFamily: 'monospace', textAlign: 'left'
}}>
<div style={{ color: '#64ffda', fontWeight: 'bold' }}>{r.name}</div>
<div style={{ fontSize: 11, color: '#888', marginTop: 4 }}>
{r.runtime === 'edge' ? "export const runtime = 'edge'" : "// default runtime"}
</div>
</button>
))}
</div>
<div style={{ background: '#0d1117', borderRadius: 8, padding: 16, marginBottom: 16 }}>
<h3 style={{ color: '#64ffda', margin: '0 0 12px' }}>Metrics</h3>
<div style={{ marginBottom: 8 }}>
<span style={{ color: '#888', fontSize: 12 }}>Latency:</span>
<LatencyBar value={selected.latency} max={150} color="#4caf50" />
</div>
<div style={{ marginBottom: 8 }}>
<span style={{ color: '#888', fontSize: 12 }}>Cold start:</span>
<LatencyBar value={selected.coldStart} max={300} color="#ff9800" />
</div>
<div style={{ marginTop: 12 }}>
<span style={{ color: '#888', fontSize: 12 }}>Regions: </span>
<span style={{ color: '#ce93d8', fontSize: 12 }}>{selected.regions.join(', ')}</span>
</div>
<div style={{ marginTop: 8 }}>
<span style={{ color: '#888', fontSize: 12 }}>Features:</span>
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
{selected.features.map(f => (
<span key={f} style={{
background: '#1a2744', border: '1px solid #333', borderRadius: 4,
padding: '2px 8px', fontSize: 11, color: '#aaa'
}}>{f}</span>
))}
</div>
</div>
</div>
<button onClick={simulatePing} style={{
background: '#4caf50', color: '#fff', border: 'none', borderRadius: 6,
padding: '8px 16px', cursor: 'pointer', fontFamily: 'monospace'
}}>
Ping (simulation)
</button>
{pings.length > 0 && (
<span style={{ color: '#888', marginLeft: 12, fontSize: 12 }}>Average: {avg}ms</span>
)}
<div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginTop: 12 }}>
{pings.map((p, i) => (
<div key={i} style={{
background: p < 50 ? '#1b5e20' : p < 100 ? '#e65100' : '#b71c1c',
borderRadius: 4, padding: '2px 6px', fontSize: 11
}}>
{p}ms
</div>
))}
</div>
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Partial Pre-rendering in Next.js 16 combines:
2. Edge Runtime in Next.js offers:
These are 2 of 9 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Create a performance monitoring system: Core Web Vitals, rendering strategy benchmarks
- Vertical ordering
Arrange the SSR request handling stages in correct order:
- Vertical ordering
Arrange the Streaming SSR stages in correct order:
- Horizontal ordering
Arrange the syntax that forces static rendering of a page in Next.js:
- Vertical ordering
Arrange the cache checking layers in Next.js in correct order:
- Horizontal ordering
Arrange the fetch syntax with disabled caching in Next.js:
- Vertical ordering
Arrange the static page generation stages in Next.js in correct order:
- Horizontal ordering
Arrange the syntax for setting page revalidation time in Next.js:
- Click in order
Arrange the revalidate syntax in fetch
- Click in order
Arrange the loading.tsx export
- Horizontal ordering
Arrange the elements in correct order: const Component -> = dynamic( -> () => import('./Component'), -> { ssr: false })
- Vertical ordering
Arrange the elements in correct order: User request arrives -> Server Component renders -> HTML sent to client -> Hydration on client
- Horizontal ordering
Arrange the tag-based revalidation call syntax in Next.js:
- Code editor
Create a complete rendering engine: 1. Hybrid Rendering Strategy - Server and Client Components 2. Caching and Revalidation - time-based and on-demand 3. Streaming and Suspense - progressive loading 4. Performance Monitoring - Core Web Vitals 5. Edge Runtime - optimal configuration
Tasks after this lesson
- QuestionPartial Pre-rendering in Next.js 16 combines:
- QuestionEdge Runtime in Next.js offers:
- Coding taskPractice: Create a performance monitoring system
- Put in orderSSR Request Flow
- QuestionData fetching in Server Components can use:
- Put in orderStreaming SSR Flow
- Put in orderStatic rendering enforcement syntax
- Put in orderData Cache Layers in Next.js
- QuestionDefault fetch caching in Next.js
- Put in orderFetch syntax with disabled cache
- Put in orderStatic Page Generation Stages
- QuestionDynamic rendering in Next.js occurs when:
- Put in orderTime-based revalidation configuration syntax
- QuestionRendering Strategies in Next.js
- QuestionRoute Segment Config in Next.js allows:
- Click in orderRevalidate syntax in fetch
- Click in orderLoading.tsx export
- Put in orderOrder: const Component -> = dynamic( -> ...
- Put in orderOrder: User request arrives -> Server Component renders -> ...
- QuestionForce-dynamic in Next.js causes:
- Put in orderTag-based revalidation syntax
- QuestionFirst cache layer in Next.js
- Coding taskHybrid Rendering System - Step by Step