This is one of the most common ways Node.js applications crash silently in production: ```js // Unhandled rejection — will crash your app app.get('/users', async (req, res) => { const users = await User.find(); res.json(users); }); ``` If User.find() throws, there's no catch. In newer Node.js versions, it crashes the process. Two ways to fix this cleanly: Option 1 — try/catch: ```js app.get('/users', async (req, res) => { try { const users = await User.find(); res.json(users); } catch (error) { res.status(500).json({ message: 'Server error' }); } }); ``` Option 2 — Wrapper utility (cleaner at scale): ```js const asyncHandler = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); ``` Option 2 keeps your routes clean and error handling centralized. Production-ready code always handles failures gracefully. #NodeJS #JavaScript #BackendDevelopment #ExpressJS
Silent Node.js Crashes: Fixing Unhandled Rejections in Express
More Relevant Posts
-
Modern React development is focused on performance visibility. And I found one interesting tool - React Scan https://react-scan.com/. It’s a lightweight tool that automatically detects performance issues in your React app — without requiring complex setup or deep profiling knowledge. It automatically tracks things like: - unnecessary re-renders - component update frequency - inefficient component structures Example usage: - CLI (no code changes) npx react-scan@latest http://localhost:3000 - Script tag <script crossOrigin="anonymous" src="//https://lnkd.in/evfJKd8f"></script> - NPM integration npm install -D react-scan For modern React development — especially in complex apps — it’s a huge productivity boost. #react #frontend #webdev #performance #javascript #reactjs
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
-
-
I kept wondering why my React app was calling the same API multiple times… 🤯 At first, I thought it was a small issue. But as the project grew, it became a real problem: * Repeated API calls * Too much state handling (loading, error, data) * Debugging became painful All because I was using `useEffect` for API calls. Then I tried something different — **React Query**. And honestly, it changed the way I handle server data: ✅ Automatic caching ✅ Built-in loading & error handling ✅ Cleaner, more maintainable code The biggest realization for me: 👉 *useEffect is not meant for managing server state.* I wrote a short article sharing what I learned and how I fixed these issues in a real project 👇 🔗 https://lnkd.in/gPMTcQBw If you're working with React, this might save you some debugging time. Would love to hear how you're handling API calls in your apps 👇 #React #JavaScript #PerformanceOptimization #WebDevelopment #ReactQuery
To view or add a comment, sign in
-
Most React developers use keys wrong in lists. And it silently breaks their app. 😅 This is what everyone does: // ❌ Using index as key {users.map((user, index) => ( <UserCard key={index} user={user} /> ))} Looks fine. Works fine. Until it doesn't. The problem: If you add/remove/reorder items — React uses the index to track components. Index changes → React thinks it's a different component → Wrong component gets updated → Bugs that are impossible to debug. 💀 Real example: // You have: [Alice, Bob, Charlie] // You delete Alice // Now: [Bob, Charlie] // Index 0 was Alice, now it's Bob // React reuses Alice's DOM node for Bob // State gets mixed up! // ✅ Always use unique ID as key {users.map((user) => ( <UserCard key={user.id} user={user} /> ))} Rule I follow: → Never use index as key if list can change → Always use unique stable ID → Only use index for static lists that never change This one mistake caused a 2 hour debugging session for me. 😅 Are you using index as key? Be honest! 👇 #ReactJS #JavaScript #Frontend #WebDevelopment #ReactTips #Debugging
To view or add a comment, sign in
-
-
Most developers try to optimize React apps… without knowing what’s actually slow. That’s the problem. Before you optimize… You need to measure. That’s where the React Profiler comes in 🔍 ⚡ What is React Profiler? A tool (inside React DevTools) that shows: • Which components are re-rendering • How long each render takes • Why a component re-rendered 🧠 What it helps you discover • Unnecessary re-renders • Slow components • Expensive computations • Props/state changes causing re-renders 🔍 Real example You click a button and suddenly the whole page re-renders. Profiler shows: 👉 A parent component updated 👉 All child components re-rendered 👉 Even the ones that didn’t need to 🚀 How to fix (after profiling) • Wrap components with React.memo • Use useMemo for heavy calculations • Use useCallback for stable functions • Avoid passing new object/array references 💡 Biggest mistake Optimizing blindly. Adding memoization everywhere… without knowing if it even helps. Measure → Identify → Optimize That’s the correct flow. 💡 React performance is not about writing more code. It’s about writing smarter code based on data. Have you ever used React Profiler to fix a real issue? 👇 #React #Frontend #WebPerformance #JavaScript #SoftwareEngineering #WebDevelopment
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
-
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
-
Day 22: Error Boundaries in React In real-world applications, errors can happen anytime. A single error in one component can crash the entire UI. To handle this properly, React provides: Error Boundaries 📌 What are Error Boundaries? Error Boundaries are React components that catch JavaScript errors in their child component tree and display a fallback UI instead of crashing the whole app. ✅ Prevents complete app crash ✅ Displays fallback UI ✅ Improves user experience 📌 What Error Boundaries can catch? ✔ Errors in rendering ✔ Errors in lifecycle methods ✔ Errors in constructors of child components 📌 What Error Boundaries cannot catch? ❌ Errors inside event handlers ❌ Errors in async code (setTimeout, promises) ❌ Errors in server-side rendering 📌 Example of an Error Boundary import React from "react"; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, info) { console.log("Error:", error); console.log("Info:", info); } render() { if (this.state.hasError) { return <h2>Something went wrong!</h2>; } return this.props.children; } } export default ErrorBoundary; 📌 How to use it? import ErrorBoundary from "./ErrorBoundary"; import App from "./App"; function Main() { return ( <ErrorBoundary> <App /> </ErrorBoundary> ); } Now, if any child component crashes, the app will show: 👉 "Something went wrong!" 📌 Why Error Boundaries are important? 🔥 Used in production apps 🔥 Prevents blank screens 🔥 Helps debugging errors #ReactJS #ErrorBoundary #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
⚡ A small Promise.all detail that can break your app Promise.all looks simple. Run multiple async tasks → get all results. But here’s the catch 👇 ❌ If even one promise fails, everything fails So even if 2 APIs succeed and 1 fails… you get nothing 😬 This hit me in a real project 👇 One non-critical API failed, and the entire page broke 💥 What I do now: ✅ Use Promise.all only when all results are required ✅ Use Promise.allSettled when partial data is acceptable Because sometimes… 👉 Partial data > No data Small detail. Real impact. #JavaScript #FrontendDevelopment #WebDevelopment #AsyncJS #SoftwareEngineering
To view or add a comment, sign in
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