Back to Blog

How to Integrate SecureNow with Your Next.js Application

Complete guide to adding enterprise-grade security monitoring to your Next.js app with SecureNow. Learn automatic setup, manual configuration, and best practices for production deployment.

Posted by

Integrating SecureNow with Next.js

Introduction

Next.js is one of the most popular React frameworks for building production-ready web applications, but securing these applications requires proper monitoring and threat detection. In this comprehensive guide, you'll learn how to integrate SecureNow with your Next.js application to get real-time security monitoring, performance analytics, and automatic threat detection.

SecureNow provides automatic instrumentation for Next.js applications using OpenTelemetry, giving you deep insights into API routes, server-side rendering, and client-side navigation without requiring code changes. The best part? Setup takes less than 30 seconds with our automatic installer!

Quick Installation (30 Seconds)

The fastest way to get started is to install SecureNow with npm. Our installer will automatically detect that you're using Next.js and offer to create the instrumentation file for you.

npm install securenow

🎉 Automatic Setup

When you run the install command, SecureNow will detect your Next.js project and ask: "Would you like to create the instrumentation file automatically?" Just answer Y and the installer will create all necessary files for you!

That's it! The automatic installer will create the instrumentation.ts file at your project root with all the necessary configuration. You can skip to the Configuration section below to set up your environment variables.

Manual Setup (Alternative Method)

If you skipped the automatic setup during installation, or prefer to set things up manually, you have two options:

Option 1: Use the CLI (Recommended)

Run the SecureNow initialization command to create the instrumentation file:

npx securenow init

This command will create the instrumentation.ts file at your project root with the correct configuration for Next.js.

Option 2: Create the File Manually

Create a file named instrumentation.ts in your project root directory (at the same level as your next.config.js file):

import { registerSecureNow } from 'securenow/nextjs';

export function register() {
  registerSecureNow();
}

This instrumentation file is automatically loaded by Next.js when your application starts, enabling SecureNow to monitor all requests, API routes, and server-side operations.

📁 File Location

The instrumentation.ts file must be placed at the root of your project, not inside the app or pages directory. If you're using the src directory structure, place it at the root level, outside of src.

Configuration

Step 1: Create Environment Variables

Create a .env.local file in your project root to store your SecureNow configuration. This file is automatically ignored by Git and is perfect for sensitive configuration.

SECURENOW_APPID=my-nextjs-app
SECURENOW_INSTANCE=http://your-securenow:4318

Configuration Parameters Explained

SECURENOW_APPID

Your unique application identifier. This can be any descriptive name for your application (e.g., "my-nextjs-app", "production-website", "staging-api"). This identifier helps you distinguish between different applications in your SecureNow dashboard.

SECURENOW_INSTANCE

The SecureNow collector endpoint URL where telemetry data will be sent. Replacehttp://your-securenow:4318 with your actual SecureNow instance URL. This is typically provided when you sign up for SecureNow or set up your self-hosted instance.

âš ī¸ Environment Variables

Never commit your .env.local file to version control. The .env.local file is automatically ignored by Next.js's default .gitignore, but always double-check before committing sensitive configuration.

Step 2: Enable Instrumentation Hook (Next.js 14 Only)

If you're using Next.js 14, you need to enable the experimental instrumentation hook feature in your next.config.js file. This step is not required for Next.js 15 and above, where instrumentation hooks are enabled by default.

module.exports = {
  experimental: {
    instrumentationHook: true
  }
}

If you already have other configuration in your next.config.js, simply add the experimental.instrumentationHook property to your existing configuration object.

â„šī¸ Next.js 15+ Users

If you're using Next.js 15 or later, you can skip this step entirely! Instrumentation hooks are stable and enabled by default in Next.js 15+, so no configuration changes are needed.

Running Your Application

Once you've completed the setup, start your Next.js development server:

npm run dev

For production deployments, build and start your application as usual:

npm run build
npm start

Verification

When your application starts, look for the SecureNow confirmation message in your terminal:

[securenow] ✅ OpenTelemetry started for Next.js

If you see this message, congratulations! SecureNow is now monitoring your Next.js application. Navigate to a few pages in your application to generate some traces, then check your SecureNow dashboard to see the incoming telemetry data.

✅ Next Steps

Open your SecureNow dashboard and look for traces from your application (identified by your SECURENOW_APPID). You should see traces for page loads, API routes, and server-side operations within a few seconds of using your application.

What SecureNow Monitors in Next.js

SecureNow provides comprehensive monitoring for your Next.js application, including:

  • API Routes: Automatic instrumentation of all API endpoints in your app/api/ or pages/api/ directories
  • Server Components: Monitoring of React Server Components and data fetching operations
  • Server-Side Rendering (SSR): Performance tracking for getServerSidePropsand server component renders
  • Static Generation: Monitoring of getStaticProps and generateStaticParams functions
  • Database Queries: Automatic detection of SQL injection attempts and slow queries
  • External API Calls: Tracking of fetch requests, including response times and error rates
  • Authentication Events: Monitoring of login attempts, session management, and authorization failures
  • Error Tracking: Automatic capture of unhandled errors and exceptions with full stack traces
  • Performance Metrics: Core Web Vitals, response times, and resource usage
  • Security Threats: Real-time detection of SQL injection, XSS, CSRF, and other attack patterns

Deployment to Production

Vercel Deployment

If you're deploying to Vercel, add your environment variables in the Vercel dashboard:

  • Go to your project settings in the Vercel dashboard
  • Navigate to the "Environment Variables" section
  • Add SECURENOW_APPID and SECURENOW_INSTANCE
  • Make sure to add them for Production, Preview, and Development environments as needed
  • Redeploy your application for the changes to take effect

Docker Deployment

For Docker deployments, pass environment variables through your docker-compose.ymlor Dockerfile:

# docker-compose.yml
services:
  nextjs-app:
    image: my-nextjs-app
    environment:
      - SECURENOW_APPID=my-nextjs-app
      - SECURENOW_INSTANCE=http://securenow:4318
    ports:
      - "3000:3000"

Other Platforms

For other deployment platforms (AWS, Azure, Google Cloud, etc.), refer to their documentation on setting environment variables. The process is similar: add SECURENOW_APPID and SECURENOW_INSTANCE as environment variables in your platform's configuration.

Advanced Configuration

Custom Service Name

You can customize additional OpenTelemetry settings by adding more environment variables:

SECURENOW_APPID=my-nextjs-app
SECURENOW_INSTANCE=http://your-securenow:4318
OTEL_SERVICE_NAME=production-frontend
OTEL_LOG_LEVEL=info

Multiple Environments

Use different environment files for different deployment stages:

  • .env.local - Local development
  • .env.development - Development environment
  • .env.production - Production environment

Use different SECURENOW_APPID values for each environment to separate your telemetry data in the dashboard (e.g., "my-app-dev", "my-app-staging", "my-app-prod").

Best Practices

Security

  • Never commit .env.local or other environment files containing sensitive configuration to version control
  • Use different application IDs for development, staging, and production environments
  • Restrict access to your SecureNow instance endpoint using firewall rules or VPN
  • Regularly review your SecureNow dashboard for security alerts and anomalies

Performance

  • SecureNow is designed to have minimal performance impact (typically <1% overhead)
  • Monitor your application's performance metrics in the SecureNow dashboard
  • For high-traffic applications, consider adjusting sampling rates (contact support for guidance)
  • Use SecureNow's performance insights to identify and optimize slow API routes and database queries

Development Workflow

  • Keep SecureNow enabled during development to catch issues early
  • Use the dashboard to debug API issues and trace request flows
  • Set up custom alerts for critical errors in production
  • Review security alerts regularly and incorporate fixes into your development cycle

Troubleshooting

No Traces Appearing in Dashboard

If you're not seeing any traces in your SecureNow dashboard:

  • Verify the success message appears in your terminal: [securenow] ✅ OpenTelemetry started for Next.js
  • Check that your SECURENOW_APPID and SECURENOW_INSTANCE are correctly set in .env.local
  • Ensure your SecureNow instance URL is accessible from your application's network
  • Try making a few requests to your application to generate traces
  • Check your application logs for any SecureNow error messages

Instrumentation Hook Not Working (Next.js 14)

If you're using Next.js 14 and the instrumentation isn't working:

  • Verify you've added experimental.instrumentationHook: true to next.config.js
  • Restart your development server after modifying next.config.js
  • Clear your .next build cache and rebuild: rm -rf .next && npm run dev

Build Errors

If you encounter build errors after adding SecureNow:

  • Ensure your instrumentation.ts file is at the project root, not inside app/ or pages/
  • If using JavaScript instead of TypeScript, name the file instrumentation.js
  • Check that you're importing from securenow/nextjs, not just securenow
  • Verify your Next.js version is 13.4 or higher (instrumentation hooks require Next.js 13.4+)

Dashboard Features

Once your application is sending traces to SecureNow, you can access these powerful features in your dashboard:

  • Real-Time Trace Viewer: See every request flowing through your application in real-time
  • Performance Analytics: Identify slow API routes, database queries, and external API calls
  • Security Alerts: Get instant notifications about potential security threats and attack attempts
  • Error Tracking: Comprehensive error reports with stack traces and request context
  • Custom Dashboards: Create custom views and charts for your specific monitoring needs
  • Alert Rules: Set up custom alerts based on error rates, response times, or security events
  • Trace Search: Powerful search and filtering to find specific requests or investigate issues
  • API Analytics: Detailed analytics for each API endpoint, including usage patterns and performance

Conclusion

Congratulations! You've successfully integrated SecureNow with your Next.js application. Your app now has enterprise-grade security monitoring, performance tracking, and automatic threat detection built right in.

SecureNow works transparently in the background, monitoring every request, API call, and database query without requiring any changes to your application code. The integration is zero-overhead in most cases, and the insights you gain from the telemetry data will help you build more secure, reliable, and performant applications.

As you continue developing your Next.js application, SecureNow will automatically adapt to your changes, monitoring new routes, API endpoints, and features as you add them. Make sure to check your dashboard regularly for security alerts, performance insights, and error reports.

For more advanced features, custom integrations, or enterprise support, visit our comprehensive documentation or reach out to our team at support@securenow.com.

Feedback
How to Integrate SecureNow with Your Next.js Application