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
Error Handling in Node.js: A Reusable Pattern
More Relevant Posts
-
🚀 package.json vs package-lock.json in React (and any Node project) When you create a React app, you’ll always see two important files in the root folder: package.json and package-lock.json. They work together but have different roles. 1️⃣ package.json – “Project blueprint” Created manually or via npm init / create-react-app. Stores project metadata: name, version, scripts (like start, build, test). Lists dependencies and devDependencies with version ranges (e.g. ^18.2.0). This is the file you edit when you add, remove, or update packages. 2️⃣ package-lock.json – “Exact snapshot of dependencies” Auto-generated when you run npm install. You don’t edit it manually. Locks exact versions of every dependency and sub-dependency installed. Ensures everyone on the team (and CI/CD) installs the same versions, avoiding “works on my machine” issues. Also helps faster installs because npm doesn’t need to resolve versions again. 💡 In simple terms: package.json → What packages your React app needs. package-lock.json → The exact versions that were actually installed. ✅ Best practice: Commit both files to your repo. Edit package.json when changing dependencies and let npm manage package-lock.json automatically. #React #JavaScript #NodeJS #WebDevelopment #packagejson #packagelockjson #Angular
To view or add a comment, sign in
-
Here’s something that took me a while to accept… 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. #NextJS #ReactJS #FrontendDevelopment #SoftwareEngineering #JavaScript #FullStackDevelopment #SystemDesign #WebPerformance #CleanCode #BuildInPublic #DeveloperExperience #AppArchitecture
To view or add a comment, sign in
-
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
To view or add a comment, sign in
-
Your React app isn't slow. Your folder structure is just a mess. When a React project grows, the "group by file type" approach breaks down. Putting all components in one folder, hooks in another, and utils somewhere else is a recipe for disaster. You end up scrolling through hundreds of files just to fix one bug. Here is how you structure a large React project for scale. Stop grouping by file type. Start grouping by feature. A feature-based architecture means everything related to a specific part of your app lives together. If you are working on the authentication flow, you should not have to leave the auth folder. Inside your src directory, structure it like this: src/ features/ auth/ components/ hooks/ services/ auth.slice.ts index.ts shared/ components/ Button.tsx hooks/ useClickOutside.ts utils/ formatDate.ts app/ store.ts router.tsx Why this works better: 1. High Cohesion Everything a feature needs is in one place. No more jumping between 5 different directories to understand a single workflow. 2. Strict Boundaries Features should not reach into other features' internals. Use an index.ts file to explicitly export only what is necessary. 3. Easier Onboarding New developers can look at the features folder and immediately understand what the application actually does. When a feature gets too complex, it naturally splits into smaller features. This scales infinitely better than the traditional flat structure. #reactjs #javascript #webdevelopment #frontend #softwareengineering #coding #architecture #cleancode #webdev #reactdeveloper
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
-
Your React app is slow. Here's why. 🐢 Most devs jump straight to optimization tools. But 90% of the time, the fix is simpler: 🔴 Fetching data in every component independently → Lift it up or use a global state solution 🔴 Importing entire libraries for one function → `import _ from 'lodash'` hurts. Use named imports. 🔴 No lazy loading on heavy routes → React.lazy() exists. Use it. 🔴 Images with no defined size → Layout shifts kill perceived performance 🔴 Everything in one giant component → Split it. React re-renders what changed, not what didn't. Performance isn't magic. It's just not making avoidable mistakes. Save this for your next code review. 🔖 #ReactJS #Frontend #WebPerformance #JavaScript #WebDev
To view or add a comment, sign in
-
Most React developers write custom hooks. But many of them don’t scale. You only realize this when your app grows. At first, hooks feel easy: Fetch data → store state → return it. Everything works… until: → You need the same logic in multiple places → Small changes break multiple screens → Side effects become hard to track → Debugging takes longer than expected The problem? We treat hooks like shortcuts instead of thinking about structure. What works better: → Keep hooks small and focused → Don’t hardcode logic — pass it as input → Separate fetching, logic, and UI → Return consistent values (data, loading, error) → Avoid unexpected side effects Simple mindset shift: Custom hooks are not just helpers. They define how your app handles data and logic. If a hook is poorly designed: → it slows you down later If it’s well designed: → everything becomes easier to scale Some of the React issues I’ve seen, started with bad hooks, not React itself. Have you faced this with custom hooks? #React #Frontend #JavaScript #WebDevelopment #SoftwareEngineering #ReactJS #FrontendDevelopment #Programming #CleanCode #TechLeadership
To view or add a comment, sign in
-
🚀 React 19 is here — not just updates, but smarter ways to build apps. Here are some exciting React 19 features with examples 👇 ✅ 1. Actions – Easier form submit handling async function submitAction(formData) { const name = formData.get("name"); console.log(name); } <form action={submitAction}> <input name="name" /> <button>Submit</button> </form> ✅ 2. useFormStatus() – Loading state in forms function SubmitBtn() { const { pending } = useFormStatus(); return <button>{pending ? "Submitting..." : "Submit"}</button>; } ✅ 3. useOptimistic() – Instant UI update const [items, addOptimistic] = useOptimistic( list, (state, newItem) => [...state, newItem] ); ✅ 4. use() API – Read promise directly const data = use(fetchUser()); ✅ 5. Ref as Prop function Input({ ref }) { return <input ref={ref} />; } 💡 React 19 makes forms easier, UI faster, and async handling cleaner. If you're learning React now, this version is a game changer. 🔥 #ReactJS #React19 #JavaScript #FrontendDevelopment #WebDevelopment #Programming #Developers
To view or add a comment, sign in
-
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
-
Your React app works. But is it fast? ⚡ Here are 11 performance tips every React dev should know: 1️⃣ React.memo → prevent unnecessary re-renders 2️⃣ useMemo → cache expensive calculations 3️⃣ useCallback → stable function references 4️⃣ Lazy load components → smaller initial bundle 5️⃣ Virtualize long lists → use react-window 6️⃣ Keep state local → don't over-use Redux/Context 7️⃣ Cache API responses → use React Query or SWR 8️⃣ Optimize images → WebP + loading="lazy" 9️⃣ Avoid layout thrashing → batch DOM reads & writes 🔟 No inline objects in JSX → define styles outside render 1️⃣1️⃣ Code split → dynamic imports for heavy components The golden rule? Profile first with React DevTools. Then optimize where it actually matters. Premature optimization is still a trap. 😅 Which of these do you already use? Drop it below 👇 #ReactJS #JavaScript #Frontend #WebPerformance #TechTips #WebDevelopment #FullStack
To view or add a comment, sign in
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