Logging on the server side is vital when you’re building applications with Next.js. Server-side rendering (SSR) introduces unique challenges and potential errors that client-side logs can’t capture.
Let's walk through how to integrate Errsole into your Next.js application for a clean, insightful logging experience. You’ll see how to start logging quickly using SQLite for local storage and also learn about options for more centralized solutions such as MySQL or PostgreSQL.
1. Why Server-Side Logging Is Important
When Next.js renders pages on the server, it’s crucial to have a clear view of:
- Application Health: Identify performance bottlenecks or errors impacting server-side rendering.
- Debugging: Pin down issues that never surface on the client side.
- Security and Auditing: Track suspicious or unexpected behaviors in your server logs.
A well-organized logging system makes these tasks straightforward, and Errsole provides a user-friendly way to capture and view these logs.
2. Install Errsole and Errsole-SQLite
Let’s start by installing Errsole and its SQLite storage plugin. SQLite offers a simple, file-based database—perfect for local development or small-scale projects.
npm install errsole errsole-sqlite
Tip: If you need a more centralized solution in production, Errsole also supports:
- errsole-mysql for MySQL
- errsole-postgres for PostgreSQL
- errsole-mongodb for MongoDB
3. Create a Logger File (logger.js
)
To keep your logging setup organized, we’ll create a dedicated file for initializing Errsole. Place this file in a lib
folder. By doing this, you can import your logger into all your server-side routes under pages/api
.
// lib/logger.js
import errsole from 'errsole';
import ErrsoleSQLite from 'errsole-sqlite';
// Initialize Errsole
errsole.initialize({
storage: new ErrsoleSQLite('path/to/database.sqlite')
});
// Export errsole to use throughout your app
export default errsole;
Here’s what’s happening:
-
Importing Errsole: We bring in the core
errsole
module and theerrsole-sqlite
plugin. - Initialize: We configure Errsole to store logs in an SQLite database.
- Export: We export our initialized logger so it can be reused across your project.
4. Use the Logger in API Routes
Now that we have our logger set up, let’s see how to log events in a Next.js API route. Any file in the pages/api
directory runs on the server side, making it the perfect place for server logs.
// pages/api/hello.js
import logger from '../../lib/logger';
export default function handler(req, res) {
// Log an info message
logger.info('API /hello was called');
// Simulate an error scenario
const errorHappened = true;
if (errorHappened) {
logger.error('Something went wrong in /hello!');
}
res.status(200).json({ message: 'Hello from Next.js + Errsole!' });
}
Logging Levels
Errsole supports various log levels (info
, error
, warn
, etc.), so you can categorize logs by severity:
- info: General operational messages.
- warn: Something unexpected but not breaking.
- error: An error that needs immediate attention.
Using these levels consistently makes filtering and searching through logs much easier down the line.
5. Viewing Logs in the Errsole Dashboard
One of Errsole’s standout features is its Web Dashboard, which displays real-time logs and error insights in a central location.
After completing the setup, you can access the Errsole Web Dashboard through the following methods:
Local Environment: Open your web browser and visit http://localhost:8001/.
Remote Server: If you have deployed Errsole on a remote server, use the server's IP address or domain name followed by the port number (e.g., YourServerIP:8001 or YourDomain:8001).
Once done, you’ll see:
- Timeline and Filtering: Search logs by date, severity, or message content.
- Error Stacks: Detailed error context, including stack traces.
- Real-time Updates: Watch logs appear as they happen.
- Collaboration: Invite your teammates to join and work together to monitor logs effectively.
Advanced Tip: For multi-app setups, you can assign different table prefixes or database files for each project to keep logs separate.
6. Centralized Logging (MySQL, PostgreSQL, etc.)
If your application is at scale or you need advanced reporting capabilities, consider integrating a more robust database.
Example: Using MySQL
// lib/logger.js
import errsole from 'errsole';
import ErrsoleMySQL from 'errsole-mysql';
errsole.initialize({
storage: new ErrsoleMySQL({
host: 'mysql-host',
user: 'database-user',
password: 'database-password',
database: 'database-name'
})
});
export default errsole;
Similarly, you can use errsole-postgres, errsole-mongodb, or other supported databases for comprehensive log management.
7. Configure NGINX
If your app is behind an NGINX reverse proxy, you can configure access to the Errsole Web Dashboard by adding the following lines to your NGINX configuration file:
location = /helloworld/logs {
return 301 /helloworld/logs/;
}
location /helloworld/logs/ {
proxy_pass http://localhost:8001/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
After updating the configuration, reload NGINX:
sudo nginx -s reload
You can now access the dashboard through your domain:
- For HTTP: http://YourDomain/helloworld/logs/
- For HTTPS: https://YourDomain/helloworld/logs/
Note: Replace /helloworld/logs
with your desired log path.
8. Advanced Configuration
Option | Type | Description |
---|---|---|
storage |
ErrsoleSQLite ErrsoleMongoDB ErrsoleMySQL ErrsolePostgres |
Required. Specify the storage backend along with connection details. |
collectLogs | Array of Strings |
Optional. Default: ['error', 'info'] . By default, Errsole collects both error and info logs. To collect only error logs, set this to ['error'] . To disable log collection entirely, set this to an empty array, [] . |
enableConsoleOutput | Boolean | Optional. Control whether log output is shown in the console. |
exitOnException | Boolean |
Optional. Default: true . By default, Errsole exits the process after capturing an uncaught exception. To disable this behavior, set exitOnException to false . |
enableDashboard | Boolean |
Optional. Default: true . Enable or disable the web dashboard feature. |
port | Number |
Optional. Default: 8001 . Specify the network port for the web dashboard. |
path | String |
Optional. Default: / . Define the base path for accessing the web dashboard. |
appName | String | Optional. Specify the name of the app. |
environmentName | String |
Optional. Default: process.env.NODE_ENV . Specify the deployment environment. |
serverName | String | Optional. Default: the hostname of the machine. Specify the name of the server. |
9. Best Practices for Logging
- Use Descriptive Messages: Make sure your log messages provide clear context—this helps when revisiting them in the future.
- Avoid Over-Logging: Log only what’s necessary. Too many logs can obscure important information and increase storage costs.
- Rotate or Archive: In production, make sure to rotate logs periodically to keep your storage in check.
Conclusion
By integrating Errsole into your Next.js server, you’ll gain real-time visibility into your application’s health and performance. Whether you choose SQLite for local development or a more advanced database like MySQL or PostgreSQL for production, Errsole offers a user-friendly solution to capture, store, and review all your server-side logs in one place.
Key Takeaways:
- Initialize Errsole in a dedicated
logger.js
file underlib/
to keep things organized. - Import this logger throughout your server routes for consistent, structured logging.
- Leverage the Errsole dashboard to view logs, filter them, and troubleshoot issues quickly.
- Scale to centralized logging options (MySQL, PostgreSQL, etc.) as your application grows.
With this setup, you can confidently develop and maintain a robust Next.js application, keeping a close eye on everything happening behind the scenes! Enjoy the enhanced clarity and peace of mind that come with a proper logging strategy.
A Next.js application with server-side logging using Errsole and MySQL. Clone or download the repository to experience it in action.
GitHub Code: nextjs-server-log-viewer
Top comments (0)