Replace console.log() with Debuggers | Next.js | TypeScript

Prajeet Kumar Thakur
readytowork, Inc.
Published in
5 min readOct 5, 2023

Are you tired of cluttering your code with numerous console log statements? Whether it’s for verifying output, checking correctness, or tracing code flow, many of us have relied on log statements throughout our coding journey. However, there’s a better way to achieve all this and more while maintaining control, flexibility, and customizability. It’s called debuggers.

We are going to learn how to use these debuggers in our Next.js project, so that you don’t have to write another console.log statement ever.

Creating our Next.js project

Enter the following command in the terminal:

npx create-next-app@latest nextjs-blog --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"

Proceed by entering “y” in the terminal, then enter the following commands:

cd nextjs-blog
npm run dev

This should be the running application on localhost:3000

Edit the main file

Let’s work with data retrieval from a public API to provide you with a real and practical illustration of debugger usage. In this example, we’ll access Star Wars data, focusing on details about the iconic character, Luke Skywalker.

To begin, open and edit the ‘pages/index.js’ file and insert the following code:

import { useEffect, useState } from 'react';
import styles from '../styles/Home.module.css';

export default function Home() {
const [character, setCharacter] = useState(null); // State to store the fetched character data

useEffect(() => {
// Define the API endpoint URL
const apiUrl = 'https://swapi.dev/api/people/1/';

// Fetch character data from the API
fetch(apiUrl)
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the response body as JSON
})
.then((data) => {
setCharacter(data); // Update the state with the fetched character data
})
.catch((error) => {
console.error('There was a problem with the fetch operation:', error);
});
}, []); // The empty dependency array ensures this effect runs only once when the component mounts

return (
<div className={styles.container}>
{character && (
<div>
<h1>{character.name}</h1>
<p>Height: {character.height} cm</p>
<p>Mass: {character.mass} kg</p>
<p>Hair Color: {character.hair_color}</p>
<p>Skin Color: {character.skin_color}</p>
<p>Eye Color: {character.eye_color}</p>
<p>Birth Year: {character.birth_year}</p>
<p>Gender: {character.gender}</p>
</div>
)}
</div>
);
}

This should be the expected result:

Editing the launch.json file

The configuration in the launch.json file is for debugging a Next.js application using Google Chrome as the debugging target. Here's a short explanation of what each key does:

  • "name": The name of this debugging configuration, which will be displayed in Visual Studio Code's debugger dropdown.
  • "type": Specifies the debugger type, which is "chrome" in this case for debugging in Google Chrome.
  • "request": Indicates that we want to "launch" a new instance of Google Chrome for debugging.
  • "url": The URL where your Next.js application is running in development mode (typically http://localhost:3000).
  • "webRoot": The root directory of your Next.js project where your source code is located. The debugger uses this path to map your source code files correctly for debugging purposes. In this example, it's set to ${workspaceFolder}/nextjs-blog, assuming your Next.js project is in a folder named nextjs-blog inside your workspace folder.
{
"version": "0.2.0",
"configurations": [
{
"name": "Next.js: Chrome",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/nextjs-blog"
}
]
}

Now, to use the debugger, click the debugger tab on the sidebar of VSCode and click the Run debugger option:

We’ll incorporate breakpoints at specific locations in our code to control the application’s flow. To set a breakpoint, hover your cursor over a line, and a faint red dot will appear to the left of the line number. Clicking on it will turn it into a vibrant red, signifying that a breakpoint has been established at that line.

Here’s a list of the breakpoints we’ve included in our codebase.

Debugger toolbar

Then, run the debugger. A debugger toolbar appears:

These have the following functions:

  1. Start Debugging (F5):
  • Starts the debugging process.
  • Launches your application in debug mode.
  • Allows you to set breakpoints and step through code.

2. Pause (Pause button or Ctrl+Break):

  • Pauses the execution of your program.
  • Useful for halting execution to inspect the current state and variables.

3. Step Over (F10):

  • Advances the debugger to the next line of code.
  • If the current line contains a function call, it will execute the entire function and move to the next line in the current context.

4. Step Into (F11):

  • If the current line contains a function call, it enters the function and starts debugging within that function’s context.
  • Allows you to dive into the details of function calls.

5. Step Out (Shift+F11):

  • When you’re inside a function and want to return to the calling function, use this button.
  • It continues execution until it exits the current function and returns to the calling function.

These buttons are essential for controlling the flow of your debugging session, inspecting variables, and navigating through your code to identify and fix issues.

Viewing the debugging console

Here is the debugger console, which is far better than the console.log statements we have been using so far:

Here, you can see that, we can see much more detailed data of what the response variable consists of which we would not have been able to see by simply console.logging.

Next, click the “Continue(F5)” button:

The debugger will advance to the next breakpoint, revealing the contents of the ‘character’ variable and the specific data it contains. We’re extracting only the desired ‘values’ for display on our webpage.

To proceed, you can click the ‘Continue’ button, which will navigate through the remaining breakpoints. To conclude our debugging session, press ‘Step Out (Shift + F11).

Conclusion

In this article, we’ve discovered a dependable and professional method for logging and analyzing variables and data in our code, enabling more efficient debugging. Additionally, we’ve explored additional features like ‘watch’ and ‘call stack,’ which offer further insights into our code. Take the time to experiment with these tools to become a debugging expert and make the debugger your trusted companion in your coding endeavors.
Happy coding!

--

--