Having trouble getting the Next.js Custom Server to function properly with Firebase

I have deployed my Next.js App on Firebase and I am using a custom server (server.ts) to launch the app (node src/server.ts). The code for the server.ts file along with firebaseFunctions.js is provided below. The server.ts file works fine locally, which means the proxy is functioning properly. However, when deployed on Firebase, it doesn't seem to work. Can someone please suggest a solution to this issue?

// @ts-ignore
const express = require("express");
const next = require("next");
const { createProxyMiddleware } = require("http-proxy-middleware");

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const API_URL = process.env.API_URL;
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  console.log("sercer")

  server.use(
    "/api",
    createProxyMiddleware({
      target: "https://tus-schedule-api.herokuapp.com",
      changeOrigin: true,
    })
  );

  server.get("/super_test", (req, res) => {
    return res.status(200).send();
  });

  server.all("*", (req, res) => {
    return handle(req, res);
  });

  server.listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});

const { join } = require("path");
const { https } = require("firebase-functions");
const { default: next } = require("next");

const isDev = process.env.NODE_ENV !== "production";
const nextjsDistDir = join("src", require("./src/next.config.js").distDir);

const nextjsServer = next({
  dev: isDev,
  conf: {
    distDir: nextjsDistDir,
  },
});
const nextjsHandle = nextjsServer.getRequestHandler();

exports.nextjsFunc = https.onRequest((req, res) => {
  return nextjsServer.prepare().then(() => nextjsHandle(req, res));
});

Answer №1

Dealing with a similar issue, I found that tinkering around eventually led to a resolution. Below is a streamlined cloud function example that worked both locally and when deployed to Firebase Cloud Functions.

import * as functions from 'firebase-functions';
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
export const expressApi = functions.https.onRequest(app);

I also configured my hosting rewrites as shown below:

  "hosting": 
    "rewrites": [
      {
        "source": "**",
        "function": "expressApi"
      }
    ]
  }

I recommend trying this example to see if it resolves your issue. Simplify your code to pinpoint the problem area.

Additionally, consider the following tips:

  • Ensure you are using the latest firebase tools: npm install -g firebase-tools (Version 8.4.3 for me)
  • Delete everything in "\functions\node_modules" and run npm install
  • Reboot your computer to clear cached data that may be causing issues.

Best of luck!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Step-by-step guide on initiating a new NextJS project with the help of PM

Whenever I attempt to run my Next.js project with PM2, I keep encountering errors even after I've already built it. Any suggestions on how to address this issue? Surprisingly, everything runs smoothly without any hiccups when I use npm start instead. ...

Encountering the error "TypeError: Unable to access properties of null" when attempting to set up NextJS

Currently following the official tutorial at: https://nextjs.org/learn/react-foundations/installation Upon executing the command: npm install react@latest react-dom@latest next@latest An error was encountered: npm error Cannot read properties of null (re ...

Ensuring that a service is completely initialized before Angular injects it into the system

When Angular starts, my service fetches documents and stores them in a Map<string, Document>. I use the HttpClient to retrieve these documents. Is there a way to postpone the creation of the service until all the documents have been fetched? In ot ...

Effortless code formatting with VS Code for TypeScript and JavaScript

Does anyone know of any extensions or JSON settings that can help me format my code like this: if(true) { } else { } Instead of like this: if(true){ } else { } ...

What is the process of creating a for loop in FindById and then sending a response with Mongoose?

Is there a way to get all the data in one go after the for loop is completed and store it in the database? The code currently receives user object id values through req.body. If the server receives 3 id values, it should respond with 3 sets of data to th ...

Using various conditions and operators to display or conceal HTML elements in React applications, particularly in NextJS

I am seeking ways to implement conditional logic in my React/Next.js web app to display different HTML elements. While I have managed to make it work with individual variable conditions, I am encountering difficulties when trying to show the same HTML if m ...

Omit functions from category

This question reminds me of another question I came across, but it's not quite the same and I'm still struggling to figure it out. Basically, I need to duplicate a data structure but remove all the methods from it. interface XYZ { x: number; ...

How can Firebase and Ionic be used to customize the password reset template for sending verification emails and more?

I'm facing an issue with firebase's auth templates not supporting my native language. Is there a way to customize the password reset template to also handle verification and email address change emails? ...

Ways to stop Next JS 13 from automatically preloading pages

While using my app that is connected to Firebase, I have noticed that each time a page loads, my usage count exceeds due to the Next JS preloading feature. This unexpected increase in cost is concerning. How can I prevent Next JS 13 from preloading? I susp ...

What is the best way to fetch the chosen item in an Angular select dropdown

I am working on a dropdown that populates with items of type ObjectA. item.component.html: <label>items list: <select formControlName="itemsCtl" (change)="onChange()"> <option *ngFor="let item of itemList" [value]="item">{{i ...

"What could be causing my React Native app to build without any issues even though the TypeScript compiler is throwing

Recently, I decided to explore TypeScript in combination with Expo. I took the time to set up linter and formatter integrations like typescript-eslint to help me catch errors while coding. Periodically, I run npx tsc to ensure my code compiles correctly an ...

The Next.js next-auth signIn feature will automatically redirect to the http://localhost:3000/api/auth/error endpoint

Recently dipping my toes into the world of next.js. I'm currently working on implementing a login feature in my React web app using next-auth locally. However, whenever I click the login button, it redirects me to "http://localhost:3000/api/auth/error ...

How to Pass a JSON Object to a Child Component in Angular and Display It Without Showing "[Object

Need help with my API call implementation. Here's a snippet from my Input component: Input.html <form (submit)="getTransactions()"> <div class="form-group"> <label for="exampleInputEmail1"></label> <input type="t ...

Navigate directly to a specific section on the current webpage using the URL feature in Next.js

I've encountered an issue with Next.js 12.2.5 where I created a section with a specific ID for user redirection, but whenever I try to access the URL with the anchor and section ID (e.g., http://localhost:3000/mx#contact-form), I receive the error mes ...

Using createStyles in TypeScript to align content with justifyContent

Within my toolbar, I have two icons positioned on the left end. At the moment, I am applying this specific styling approach: const useStyles = makeStyles((theme: Theme) => createStyles({ root: { display: 'flex', }, appBar: ...

Excessive use of the findMany method in Next.js with Prisma can lead to an overflow

I am currently facing an issue where my website is loading slowly because I am fetching all items from a table and displaying them inside a carousel. The table has too many entries, and I need to find a solution to only fetch a few items, display them in a ...

Create a new object containing a series of function expressions, but exclude the first function parameter

In my current setup, I have a variable called storePattern const storePattern = { state: { }, mutations: { }, actions: {}, modules: { modal: { actions: { openModal(store, name: string): boolean { console.log('Op ...

Launching a web application on Vercel, the back-end has yet to be initialized

I am currently working on a Next.js/TypeScript web application project hosted on Vercel's free tier. To run my project, I use npm run dev in the app folder to start the front end and then navigate to the back-end folder in another terminal and run npm ...

What is the method for dynamically assigning a name to ngModel?

I have the following code snippet: vmarray[]={'Code','Name','Place','City'} export class VMDetail { lstrData1:string; lstrData2:string; lstrData3:string; lstrData4:string; lstrData5:string; ...

Determine whether an element is visible following a state update using React Testing Library in a Next.js application

I'm looking to test a NextJS component of mine, specifically a searchbar that includes a div which should only display if the "search" state is not empty. const SearchBar = () => { const [search, setSearch] = useState(""); const handleSear ...