Skip to content

Conversation

@chalosalvador
Copy link
Contributor

Description

Problem

Next.js external URL rewrites (rewrites to http:// or https:// destinations) fail with 504 Gateway Timeout when deployed to Firebase Hosting.

Related issues:

Example configuration that fails:

// next.config.ts
async rewrites() {
  return [
    {
      source: '/proxy/:path*',
      destination: 'https://api.example.com/:path*',
    },
  ];
}

Root Cause

In incomingMessageFromExpress(), a new Socket() is created which is disconnected (has no network connection):

const socket = new Socket();  // Disconnected socket
const incomingMessage = new IncomingMessage(socket);

When Next.js handles external rewrites, it uses http-proxy internally, which relies on the socket to pipe the response back to the client. With a disconnected socket, the response cannot be delivered, causing the request to hang until Cloud Functions times out (504).

Solution

Intercept external URL rewrites before they reach Next.js's internal http-proxy. The new handleExternalRewrite() function:

  1. Reads routes-manifest.json to identify external rewrites
  2. Matches incoming requests against rewrite patterns
  3. Proxies directly using fetch() (which doesn't depend on socket state)
  4. Handles response headers properly (skipping content-encoding, transfer-encoding, content-length to avoid decompression issues)
  5. Returns the response via Express's res.send()

This bypasses the broken code path entirely while maintaining full compatibility with Next.js rewrite semantics.

Changes

  • src/next.js/index.ts: Added handleExternalRewrite() function and external rewrite interception in the handle() export

Testing

  1. Create a Next.js app with external rewrites:
// next.config.ts
async rewrites() {
  return [
    {
      source: '/proxy/:path*',
      destination: 'https://jsonplaceholder.typicode.com/:path*',
    },
  ];
}
  1. Deploy to Firebase Hosting with firebase deploy

  2. Test the proxy endpoint:

curl https://your-site.web.app/proxy/posts/1

Expected: Returns JSON from jsonplaceholder API
Before fix: 504 Gateway Timeout after ~60 seconds


- Introduced caching for external rewrites from the routes manifest.
- Implemented functions to load and handle external URL rewrites, ensuring proper proxying in Cloud Functions.
- Enhanced request handling to support external rewrites before processing by Next.js.
@chalosalvador chalosalvador requested review from a team as code owners January 26, 2026 21:26
@gemini-code-assist
Copy link

Summary of Changes

Hello @chalosalvador, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves a critical issue where Next.js applications deployed on Firebase Hosting would encounter 504 Gateway Timeout errors when attempting external URL rewrites. The problem stemmed from Next.js's internal http-proxy relying on a disconnected socket within the Cloud Functions environment. The solution introduces a mechanism to detect and directly handle these external rewrites using the fetch API, effectively bypassing the problematic code path and ensuring seamless proxying to external destinations.

Highlights

  • External Rewrite Fix: Addresses a 504 Gateway Timeout issue encountered when Next.js external URL rewrites are deployed to Firebase Hosting, caused by Next.js's internal http-proxy failing due to a disconnected socket.
  • Direct Proxying Implementation: Introduces a new handleExternalRewrite function that intercepts external rewrites before Next.js processes them. This function directly proxies requests using the fetch() API, bypassing the problematic internal http-proxy.
  • Rewrite Configuration Parsing: The solution includes logic to read and cache external rewrite configurations from the .next/routes-manifest.json file, allowing dynamic matching of incoming requests against defined rewrite patterns.
  • Robust Header Handling: Ensures proper handling of response headers during proxying by explicitly excluding transfer-encoding, content-encoding, and content-length to prevent decompression and other potential issues with the proxied response.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request provides a solid fix for the 504 Gateway Timeout issue affecting Next.js external URL rewrites on Firebase Hosting. The approach of intercepting and proxying these requests with fetch before they reach Next.js's problematic internal proxy is well-reasoned and effectively addresses the root cause. The implementation is clean and includes helpful comments. I've included a few suggestions to enhance error handling and improve performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant