#prevent next build trying to connect to my redis

1 messages · Page 1 of 1 (latest)

dusky rampart
#

npm run build would attempt to make connections to my redis which I only use for rate limit. How would I prevent this?

worthy ironBOT
#

Hi @dusky rampart. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To prevent Next.js from attempting to connect to Redis during the build process, you can use environment variables to conditionally create the Redis client. This approach allows you to skip Redis connection attempts during the build phase while still maintaining the functionality for rate limiting in production.

Here's a solution based on the information from the knowledge sources:

  1. In your Redis connection setup file (e.g., cache-handler.js or wherever you initialize Redis), you can use an environment variable to determine whether to create the Redis client:
const { PHASE_PRODUCTION_BUILD } = require('next/constants');

// ... other imports

const CacheHandler = CacheHandler.onCreation(async () => {
  // Skip Redis connection during build
  if (process.env.NODE_ENV === 'production' && process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD) {
    console.info('Skipping Redis connection during build');
    return {
      handlers: [createLruHandler()], // Use a local LRU cache instead
    };
  }

  let client;
  // ... rest of your Redis connection logic
});

module.exports = CacheHandler;
  1. In your next.config.js, you can set the NEXT_PHASE environment variable:
/** @type {import('next').NextConfig} */
const { PHASE_PRODUCTION_BUILD } = require('next/constants');

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_BUILD) {
    process.env.NEXT_PHASE = PHASE_PRODUCTION_BUILD;
  }
  
  return {
    // Your other Next.js config options
  };
};

This approach ensures that during the build process (npm run build), the Redis connection is not attempted. Instead, it falls back to a local LRU cache or skips caching altogether, depending on your needs.

#

For rate limiting specifically, you can implement it in a way that only runs on the server-side, not during the build process. You might consider using Vercel's Edge Middleware (https://vercel.com/docs/concepts/functions/edge-middleware) for rate limiting, which runs separately from your build process.

Remember to properly handle cases where Redis might not be available in your rate limiting logic to ensure your application remains functional even if Redis connection fails.

Github Issue: Next.js with custom cache handler fails to serve pre-rendered pages (https://github.com/vercel/next.js/issues/58094)
Github Issue: Next.js 13 app dir: Fast Refresh (hot reloading) causes database connection exhaustion (https://github.com/vercel/next.js/issues/45483)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: