Understanding Route Handlers in Next.js (App Router) Been working with the Next.js App Router recently, and one feature I think more developers should take advantage of is Route Handlers. They let you build backend logic directly inside your /app directory using the Web Request/Response APIs — no separate API routes needed. Here’s why they’re powerful: 🔵 1. Simple, file‑based backend logic Just drop a route.ts file anywhere inside /app: export async function GET(request: Request) {} Next.js automatically maps it to an API endpoint. Clean, predictable, and colocated with your UI. 🟠 2. Full support for HTTP methods GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS — all supported out of the box. If a method isn’t implemented, Next.js returns 405 Method Not Allowed automatically 🔵 3. Extended NextRequest & NextResponse You get helpers for cookies, headers, URL parsing, redirects, and more — perfect for auth, data validation, and secure server logic. 🟠 4. Smart caching behavior GET handlers can be cached using export const dynamic = 'force-static' Other methods always run dynamically Prerendering stops when you access runtime data (headers, cookies, DB queries, etc.) 🔵 5. Great for Backend‑for‑Frontend (BFF) patterns You can fetch external APIs, sanitize responses, enforce auth, and return exactly what your React components need — all inside the same route segment. Route Handlers feel like the missing piece between frontend and backend. They keep your logic close to your UI, reduce boilerplate, and make Next.js a true full‑stack framework. #Nextjs #ReactJS #WebDevelopment #FullStackDeveloper #JavaScript #TypeScript #APIDevelopment #BackendForFrontend #WebEngineering #CodingTips
Next.js Route Handlers Simplified
More Relevant Posts
-
Designing Reusable Behavior in React with Custom Hooks ⚛️ Before custom hooks, every single page in my React app looked like this: useState for data. useState for loading. useState for error. useEffect to fetch. Axios call. Error handling. Toast on success. Invalidate cache manually. Multiply that by 30+ pages. That's hundreds of lines of repeated logic. So I stopped copy-pasting and started building. → useCustomQuery One hook. Every GET and POST request in the entire app. TanStack Query under the hood — caching, gcTime, pagination, enabled flag — all configurable. Pass the URL, method, and queryKey. Get clean data back. Zero boilerplate in the component. → useCustomMutation One hook. Every create, update, and delete operation. Automatic query invalidation after success. Toast notification fires itself. Modal closes itself. Session expiry triggers logout via Axios interceptor. The component calls mutate() and forgets about the rest. → useDebounceSearch 15 lines. Proper setTimeout cleanup.Configurable timer. Every search input in 30+ pages uses this one hook. Saves hundreds of unnecessary API calls every day.Search changes → skip resets to 0 automatically. The component just renders. It has no idea how any of it works. The result? ✦ Components went from 80 lines to 20 ✦ New pages now take half the time to build ✦ Bugs are isolated — fix once, fixed everywhere ✦ The entire team uses complex logic without understanding every detail Custom hooks didn't just clean up my code. They changed how I think about building React apps. Are you still writing the same logic in every component — or have you made the switch to custom hooks? #ReactJS #Frontend #JavaScript #TypeScript #WebDevelopment #CleanCode #SoftwareEngineering #FrontendDevelopment #ReactHooks #TanStackQuery
To view or add a comment, sign in
-
🚀 How I eliminated redundant API calls in React (and improved performance) One common issue in React applications is unnecessary API calls, which can slow down the UI and increase backend load — especially in large-scale apps. Here’s what worked for me: ✅ Used a centralized data fetching strategy to fetch once and reuse across components ✅ Leveraged React Query / Redux / Context as a single source of truth ✅ Enabled caching and request deduplication to avoid repeated API calls ✅ Added conditional fetching (only call APIs when needed) ✅ Decoupled data fetching from UI components for better scalability 📈 Results: • Reduced redundant network requests • Faster page load times • Improved UI responsiveness • Better performance in data-heavy applications 💡 Key takeaway: Performance optimization isn’t just about rendering — it’s about how efficiently your application fetches and manages data. What strategies have you used to optimize API calls in React apps? #React #Frontend #WebDevelopment #Performance #JavaScript #NextJS
To view or add a comment, sign in
-
-
Most Node.js apps don't crash because of bad code. They crash because of bad error handling. Here's a pattern I use in almost every project: Instead of letting unhandled promise rejections silently kill your server, wrap your async route handlers in a reusable utility: const asyncHandler = (fn) => (req, res, next) => { Promise.resolve(fn(req, res, next)).catch(next); }; app.get('/user/:id', asyncHandler(async (req, res) => { const user = await getUserById(req.params.id); if (!user) throw new AppError('User not found', 404); res.json(user); })); app.use((err, req, res, next) => { res.status(err.status || 500).json({ message: err.message || 'Internal Server Error', }); }); That's it. One wrapper, one central error middleware, and your entire app handles errors consistently. The key insight: errors should flow to one place, not be scattered across every route with try/catch blocks copy-pasted everywhere. A custom AppError class lets you attach HTTP status codes and meaningful messages, so your API responses stay predictable for frontend teams. This also makes logging much easier — you intercept everything in one middleware and send it to whatever logging service you use. Small pattern, big payoff. Your teammates will thank you, and your on-call rotations will get a lot quieter. What's the error handling pattern you swear by in your Node.js projects — do you use something similar, or have you found a better approach? #nodejs #backend #javascript #softwaredevelopment #webdevelopment
To view or add a comment, sign in
-
-
CORS becomes very easy to understand with one real example. Imagine this: You’re building a React app on http://localhost:3000 Your backend API is running on http://localhost:8000 From your frontend, you make a request: fetch("http://localhost:8000/api/profile") Looks normal, right? But the browser sees this as: Frontend → localhost:3000 Backend → localhost:8000 Same machine. Same localhost. Different port. And that different port is enough for the browser to say: “Hold on — this is a different origin. I need permission first.” So before sending the real request, the browser asks your backend: “Is localhost:3000 allowed to access you?” That’s the CORS check. If your backend responds with: Access-Control-Allow-Origin: http://localhost:3000 The browser allows the request. If not, it blocks it and throws the CORS error. That’s why this fails: fetch("http://localhost:8000/api/profile") Not because your API is broken. Not because React failed. But because the browser is protecting the user. And that’s the key thing most beginners miss: CORS is not a server error. It’s the browser asking the server for permission. Once you understand that, CORS stops feeling random. #Frontend #WebDevelopment #JavaScript #ReactJS #NodeJS #FullStack #SoftwareEngineering #Developers #TechConcepts
To view or add a comment, sign in
-
-
Build a full Next.js app for free. Every tool you actually need. 🚀 One of the biggest lies in tech is that you need money to start building. You don’t. I’ve shipped production apps with thousands of users and paid exactly $0 for tooling. Here’s the complete free stack 👇 💻 Next.js + Vercel Deploy with one command. Free hobby tier. Automatic HTTPS. Custom domains. If you’re not deploying to Vercel you’re making your life harder for no reason. 🗄️ Neon / Supabase Full Postgres database on a free tier that handles real traffic. Pair it with Prisma or Drizzle for type-safe queries and you have a production-grade database for $0. 🔐 Clerk Auth Complete authentication in about 10 minutes. OAuth, magic links, session management — all free up to 10,000 monthly active users. Building auth from scratch in 2025 is a waste of time. 🎨 Shadcn UI Copy and paste beautiful components built on Tailwind CSS. No npm install, no license, no limits. Your app looks professional from day one. 📧 Resend Send transactional emails using React components. 3,000 emails per month free. The simplest email API I’ve ever used. 📊 Upstash Serverless Redis for rate limiting, caching, and background queues. The free tier handles way more than your first app will ever need. Total monthly cost: $0. Every single excuse to not start building just disappeared. Which tool are you missing from your stack? Comment below 👇 Save this and share it with a developer who thinks they can’t afford to build. 🔖 #NextJS #React #WebDevelopment #JavaScript #Frontend #Beginners #Programming #BuildInPublic #WebDev #100DaysOfCode #IndieHacker #LearnToCode #SideProject #Vercel
To view or add a comment, sign in
-
-
🚀 How I actually improved performance in Next.js (beyond the basics) After working on real production apps, I realized performance isn’t about adding more tools - it’s about removing unnecessary work from the client. Here are the changes that made a real difference: 1. App Router + React Server Components Shifted most logic to the server → significantly reduced client-side JS bundle. Less hydration = faster initial load. 2. Selective Dynamic Import Used next/dynamic with { ssr: false } for heavy components (charts, editors, maps). Load only when needed → avoid blocking the main thread. 3. Proper Image Optimization next/image handled WebP, lazy loading, and responsive sizing automatically. Improved Core Web Vitals without extra libraries. 4. Parallel & Deferred Data Fetching Replaced sequential fetching with Promise.all and Suspense. Critical data loads first, non-critical parts are deferred. 5. Caching Strategy (this is where most people get it wrong) Understanding force-cache, no-store, and revalidate is key. Wrong caching can hurt more than no caching at all. 👉 Biggest lesson: Performance isn’t about doing more - it’s about sending less and doing less on the client. Curious what strategies you’re using to optimize Next.js apps 👇 #Nextjs #WebPerformance #Frontend #ReactJS #Programming
To view or add a comment, sign in
-
-
🚀 Handling Token Expiry in React Apps using React Query (Modern Approach) 🔐 Tired of writing complex Axios interceptor logic everywhere? 🤯 There’s a cleaner and more scalable way 👇 --- 💡 Problem 👉 JWT token expires → APIs start failing with 401 👉 Handling this in every API = messy ❌ --- ⚡ Modern Solution 👉 Use React Query for global error handling 👉 Handle token expiry in one place 👉 Retry failed requests automatically --- 🔁 How It Works 1️⃣ API call via React Query 2️⃣ If 401 Unauthorized 3️⃣ Trigger refresh token API 4️⃣ Get new access token 5️⃣ Invalidate queries → auto retry ✅ --- 🧠 Why This is Powerful ✔ No repetitive error handling ✔ Built-in caching & retry ✔ Clean and scalable architecture ✔ Perfect for modern React apps --- 🔥 Interview Tip Instead of saying “I use Axios interceptors”… Say this 👇 💬 “I use React Query’s global error handling to manage token expiry. On 401 errors, I trigger a refresh token API and invalidate queries to retry them automatically. This keeps the code clean and avoids interceptor complexity.” --- ⚠️ Pro Tips 👉 Prevent multiple refresh calls using a flag 👉 Handle refresh failure → logout user 👉 Combine with secure storage (HttpOnly cookies 🔐) --- 🏆 When to Use ✔ Large-scale React apps ✔ Apps needing caching + performance ✔ Clean architecture lovers 😎 --- 💣 Final Takeaway 👉 “React Query simplifies token expiry handling by combining caching, retries, and global error handling in one place.” --- #ReactJS #ReactQuery #Frontend #JavaScript #JWT #WebDevelopment #SoftwareEngineering #InterviewPrep #CodingTips
To view or add a comment, sign in
-
The Hidden Architecture Problem Here’s something that took me a while to accept, lads… You can build a Next.js app that works perfectly fine. Pages load, data shows up, and users can click around. And yet, you could still be doing it completely wrong. Not wrong in a "this will crash" way. Wrong in a quieter way... The kind of wrong that results in 800 KB JavaScript bundles for a simple landing page. The kind of wrong that creates hidden data waterfalls, making your app feel sluggish despite being "modern." I’ve seen this in countless code reviews. I’ve seen it in projects from senior React devs. And I definitely did it myself. The issue isn’t skill. It’s a mental model problem. Next.js forces you to make decisions that React never asked you to make: Does this component live on the server or the client? Should this data be cached, revalidated, or fetched fresh? Is this a Server Action or an API route? Does it even matter? Spoiler: It’s the difference between a secure app and a data leak. In standard React, everything runs in the browser. In Next.js, every decision changes the architecture of your entire app. Get them wrong, and the app still "works," it just doesn't work the way Next.js was engineered to work. Most developers don’t realize they’re building a "React app inside a Next.js folder" until it’s too late to change. On Monday, I’ll tell you the exact moment I realized my own app was lying to me 👀 Stay tuned. #insights #technews #code #trends
To view or add a comment, sign in
-
What if you never had to build an API for your Laravel + Vue app? That's exactly what Inertia.js does. And in 2026, with v3 just released, it's better than ever. 🚀 Here's the idea: Instead of: Laravel API → CORS → token auth → Axios → state management → Vue You get: Laravel controller → Inertia → Vue component (as props) Your controllers return Inertia::render() instead of JSON. Vue components receive data as props. Laravel handles routing, auth, validation, and sessions — exactly as always. No duplication. No boilerplate. What Inertia v3 ships (March 2026): → No more Axios — built-in XHR client cuts ~15KB from your bundle → useHttp hook — reactive HTTP requests outside of page navigation (search, autocomplete) → Optimistic updates — instant UI changes with automatic rollback on error → SSR works in npm run dev — no more separate Node.js process during development → useLayoutProps — clean page-to-layout communication, no event bus needed And the features that were already amazing: ✔ useForm — Laravel validation errors mapped to fields automatically ✔ Shared data — auth user, flash messages available on every page ✔ Persistent layouts — sidebar never re-renders between navigations ✔ Inertia::optional() — lazy load expensive data only when needed I wrote the complete deep dive for installation to shared data, forms, persistent layouts, and when NOT to use Inertia. Are you already using Inertia.js? What stack are you pairing it with? #Laravel #InertiaJS #Vue #PHP #WebDevelopment #FullStack #100DaysOfBlogging
To view or add a comment, sign in
-
Most devs think Server Components vs Client Components is about "where code runs." That's technically true. But it misses the point. After 3 years of building React apps, here's the mental model that finally clicked for me: 🖥️ Server Components = Your Data Layer Think of them as the backend of your frontend. They run on the server, can access databases directly, and ship ZERO JavaScript to the browser. Use them when: → Fetching data (no more useEffect waterfalls) → Reading env variables or secrets → Rendering static/heavy layouts 💻 Client Components = Your Interaction Layer These are classic React. They hydrate in the browser and handle ALL interactivity. Use them when: → You need state (useState, useReducer) → You need lifecycle hooks (useEffect) → You need event handlers (onClick, onChange) The mistake everyone makes? Thinking "Server = fast, Client = slow." Wrong. Server Components reduce your bundle. Client Components cache beautifully. The power is in MIXING them — not choosing one. Here's the real-world pattern I use: 📂 Server Component (layout + data fetching) └─ 💻 Client Component (interactive form) └─ 🖥️ Server Component (search results) Nest them. Compose them. Stop treating them like enemies. The mental shift: Server Components are not "better React." They're a different tool for a different job. Once you get this, Next.js App Router finally makes sense. #React #NextJS #WebDev #Frontend #ServerComponents
To view or add a comment, sign in
-
More from this author
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development