Troubleshooting Next.js API endpoints with VSCode

Currently, I find myself manually searching for the file (api endpoint) in the /api folder within VSCode where I need to set a breakpoint.

In my launch.json, I have the following configuration:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      "name": "Attach to application",
      "skipFiles": ["<node_internals>/**"],
      "port": 9229
    }
  ]
}

Is there a method to automatically pause or set a breakpoint whenever a request is made to a specific Next.js Api Route?

For example, let's consider an /api/data.tsx file:

import { NextApiRequest, NextApiResponse } from 'next';
import { StatusCodes } from 'http-status-codes';
import getConfig from 'next/config';

export default async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
   console.log('do some logging');
   res.status(StatusCodes.OK).json({message: 'Good job buddy!'});
}

If I want to pause at the console.log statement every time a request comes in, how can I achieve this?

Answer №1

I encountered a similar issue when trying to place red dots on the sidebar in VSCode.

Fortunately, there is a workaround available. Instead of clicking to set the red dot on the desired line, simply type "debugger" on that line. It's strange that one method works while the other doesn't - perhaps a small adjustment could enable the clicking feature to function properly? Currently, this approach has been working well for me with the API routes:

npm run dev

To attach the debugger, use the following launch.json configuration. In my case, the Next.js project was located in a subfolder within my workspace folder, so I had to adjust the configuration accordingly to match the root of the project with the $workspaceFolder.

{
    "name": "Attach",
    "port": 9229,
    "request": "attach",
    "webRoot": "${workspaceFolder}", // my project had an additional subfolder here
    "cwd": "${workspaceFolder}",     // and here
    "skipFiles": [
        "<node_internals>/**"
    ],
    "type": "pwa-node"
},

In VSCode, insert the breakpoint wherever needed like so:

handler.get(async (req, res) => {
  debugger;

  console.log....
});

You should see something similar to this setup

Answer №2

I encountered a similar issue, but managed to resolve it through a two-step process:

  1. To start, I included a line in my VSCode settings.json file:

    "debug.javascript.usePreview": false

  2. Additionally, I made sure not to use

    NODE_OPTIONS="--inspect"

After making these adjustments, you may still encounter unbound breakpoints. However, by running the application and setting the breakpoint again, it should turn red and function properly.

Update

In some cases, I faced difficulty setting breakpoints on API calls. After spending some time investigating the root cause, I discovered the problem:

When running a Next.js app, Node first executes the next script, which then spawns a child process containing your code. Next.js automatically sets NODE_OPTIONS=--inspect when in development mode, but with a different port number that changes dynamically. The CRUCIAL POINT is this: The debugging port numbers for the Next script and the child process differ, resulting in occasional inability to set breakpoints.

Here are a few scenarios:

  1. If you manually start the server in the VSCODE terminal by entering "npm run dev," VSCODE will easily locate the debugging ports and everything should work smoothly.
  2. If you launch the server outside of VSCODE from a terminal and then utilize attach, VSCODE will only attach to one port, typically linked to the Nextjs script. This explains why you might struggle to set breakpoints in your own code.
  3. Using the launch method to initiate the server in launch.json leads to a similar outcome as No.2 - breakpoints cannot be set effectively.

A simple solution exists: Either commence the server from the VSCODE internal terminal or include the following line in your launch.json:

  "autoAttachChildProcesses": true,

This configuration enables smooth debugging operations by pressing F5.

   {
      "name": "Next.js: debug full stack",
      "type": "node-terminal",
      "request": "launch",
      "command": "npm run dev",
      "serverReadyAction": {
        "pattern": "started server on .+, url: (https?://.+)",
        "uriFormat": "%s",
        "action": "debugWithChrome"
      },
      "autoAttachChildProcesses": true,
    }

No need to add NODE_OPTION='--inspect' or modify

"debug.javascript.usePreview": false
. You're all set!

Answer №3

Although it may seem like a delayed response, I wanted to share some potentially valuable information for others. Following the guidelines outlined here https://nextjs.org/docs/advanced-features/debugging proved to be successful in my case. It's important to copy the relevant section for debugging full stack applications and make sure to adjust the directory path if your code is located in a subfolder. This setup worked effectively for me:

 {
            "name": "Next.js: debug full stack",
            "type": "node-terminal",
            "request": "launch",
            "command": "npm run dev",
            "cwd": "${workspaceFolder}/client",
            "serverReadyAction": {
                "pattern": "started server on .+, url: (https?://.+)",
                "uriFormat": "%s",
                "action": "debugWithChrome"
            }
        }

Answer №4

If you're looking to run and debug NextJS/NodeJS/ExpressJS on VSC 1.91.1 in July 2024, follow these simple steps:

1 - Start by clicking here: https://i.sstatic.net/3GFaVQrl.png

2 - Next, click on this link https://i.sstatic.net/bZAZBNiU.png

Select the script you wish to run from the list provided. All scripts listed in the package.json file should be available. Personally, I tried using "Run Script: dev" https://i.sstatic.net/J4I0hr2C.png

3 - Finally, hit the run button https://i.sstatic.net/WitoQBTw.png

Answer №5

This issue has been persisting for over two years now, and it's surprising to see that the Next team hasn't taken the time to update their documentation. The solutions were available all this time.

Issue 47561

   {
      "name": "Next.js: debug full stack",
      "request": "launch",
      "type": "node",
      "runtimeArgs": ["--inspect"],
      "program": "${workspaceFolder}/node_modules/.bin/next",
      "skipFiles": ["<node_internals>/**"],
      "serverReadyAction": {
        "action": "debugWithEdge",
        "killOnServerStop": true,
        "webRoot": "${workspaceFolder}",
        "pattern": "- Local:.+(https?://.+)",
        "uriFormat": "%s"
      }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to develop a straightforward JavaScript presentation display

The slideshow will cycle through six images named 1.jpg, 2.jpg, 3.jpg, 4.jpg, 5.jpg, and 6.jpg var showarray = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg"]; var i = 0; for( i = 0; i < 6; i++) { // Is there a way to pause the script for two ...

A step-by-step guide to moving Vue .prototype to its own file

I have a couple of functions that I need to add to Vue's .prototype. However, I don't want to clutter up the main.js file. I attempted to move the prototypes like this: //main.js import "./vue-extensions/prototypes"; ...

Jest doesn't recognize the function expect(...).objectContaining

Currently, I am utilizing Jest to test the structure of an object with attributes {cart_id: 'string', payment: 'string', site: 'string'}. However, when I attempt the following: test('paymentRequest should be formatted&a ...

Using AngularJS to dynamically assign classes with values derived from an ng-repeat loop

I'm attempting to assign a class to a table row using ng-class based on the value of ng-repeat. I have searched online and found examples that involve calling a function. Is it possible to simply set ng-class with a value instead of using a function? ...

Error code 42P01 in Prisma PostgreSQL indicates that the specified table does not exist in the database

I'm attempting to execute a query that will search for items in the Item table based on how closely their title and description match a given value. Here is the query I am using: let items = await prisma.$queryRaw`SELECT * FROM item WHERE SIMILARITY(n ...

Allowing access from different domains when using Angular.js $http

Whenever I encounter a CORS issue while developing a webapp, my go-to solution is to brew some coffee. However, after struggling with it for some time, I am unable to resolve the problem this time and need assistance. Below is the client-side code snippet ...

It is essential for each child in a list to be assigned a unique "key" prop to ensure proper rendering, even after the key has been assigned (in Next

Working with Next JS and implementing a sidebar with custom accordions (created as SideAccord.js component). Data is being looped through an array with assigned keys, but still encountering the following error: Warning: Each child in a list should have a u ...

The application of knockoutjs bindings is restricted to specific ids and cannot be used on any

In my project, I have multiple views where each one applies bindings to its own tag individually. Here is a snippet of the code: (Please note that some code has been omitted for brevity. For a more complete example, you can view the full fiddle here: http ...

Navigating through React Native with TypeScript can be made easier by using the proper method to pass parameters to the NavigationDialog function

How can I effectively pass the parameters to the NavigationDialog function for flexible usage? I attempted to pass the parameters in my code, but it seems like there might be an issue with the isVisible parameter. import React, { useState } from 'rea ...

How do you write functions in ES6?

When attempting to access my namespaced store in Vue, I encountered an issue: methods: { ...mapActions('Modal', [ 'toggleActive', ]), close: () => { this.toggleActive(); } This resulted in the follow ...

Ways to verify if a firebase timestamp surpasses the present date

Would you help me with comparing a timestamp field with the current date using JavaScript? This is what I have tried so far: // Initialize an empty array to store documents let myDocs = []; // Call the getDocs function and handle the response await getDo ...

React Color Input: The input format should follow the pattern of "#rrggbb", with rr, gg, and bb being two-digit hexadecimal values

The code is functioning correctly and as expected. The background color of the squares changes when each input is modified, and the squares update once the button is pressed. During development, there was a moment when the warning mentioned appeared brief ...

Prevent repetitive content on your Node.js server

After realizing my small image hosting has many duplicate content, I am looking for a solution to prevent this issue in the future. My idea is to use either checksum or hash code so that whenever a new file is uploaded, it will be hashed and compared with ...

What causes my code to break completely when I import something?

My chrome extension has a simple function that retrieves a user's selected text using the Chrome Tabs API. I am looking to integrate a Hugging Face API in the future, but I am facing an issue. Whenever I try to import the necessary model, the Chrome T ...

Seeking assistance with using JavaScript to filter posts from Contentful for a Next.js website

Currently, I am integrating a Next.js blog with Contentful and employing queries to display posts on the homepage. While I can easily use .filter() to feature certain posts based on a boolean value, I am struggling to figure out how to fetch posts that mat ...

Verify in JavaScript whether the object from the session exists

Within View.cshtml, there is a section where I am checking for the existence of an object named Reservation in the session. <head> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") <script type="text/javascri ...

Troubleshooting: React js Project console.logs are not being displayed in the browser's

When working on my current project, I noticed that any time I try to use console.log in the dev tools, it shows as cleared. Strangely, console.log works fine in my other projects. Does anyone have an idea how to resolve this issue? Here is a screenshot of ...

Can you use an ajax post to search for a boolean in MongoDB without converting on the server side?

I am facing an issue with my mongo collection that has documents containing a boolean field: { name : "Tom", active : true } { name : "Jerry", active : false } In my application's client side, there is an element that triggers an AJAX po ...

Experiencing a problem with value formatting while attempting to implement tremor for charts in React with Next.js version 13

import { getAuthSession } from "@/lib/auth"; import { db } from "@/lib/db"; import { Card, LineChart, Text, Title } from "@tremor/react"; import Linechart from "./LineChart"; const dollarFormatter = (value: number) ...

Trouble with shadow rendering in imported obj through Three.js

After importing an object from blender and setting every mesh to cast and receive shadows, I noticed that the rendered shadows are incorrect. Even after merging the meshes thinking it would solve the issue, the problem persisted. It seems like using side: ...