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

Angular2 routing directs me to a different URL path

In my Angular2 web application, I have set up the following routes: '', '/app', '/login', '/signin', '/validate', '/error', '**': I've defined a route configuration in app.router.t ...

Unknown MUI theme colors were inputted into the styled component

I've been struggling to incorporate my theme into the styled() function in mui v5. Here's the setup I have: - ThemeProvider (@mui/material/styles) wrapped around app. - Theme created using 'createTheme' from @mui/material/styles - T ...

Tips for displaying an associative object array as td elements within a tbody in Nuxt

I'm having trouble displaying the property of an associative object array in my code. I attempted to utilize a v-for loop and wanted to showcase the property information within the td elements of a tbody. I am aware that v-data-table components have a ...

Retrieve environmental variables in next.config.js

In my next.config.js file, I have the following setup: /** @type {import('next').NextConfig} */ const nextConfig = { output: "standalone", // When set, this URL prefix should be used to fetch static content instead of serving it dir ...

Using ts-loader with Webpack 2 will result in compatibility issues

Lately, I've been working on setting up a basic Angular 2 (TypeScript) application with Webpack 2 for bundling. However, I'm encountering numerous errors when using ts-loader to process TypeScript (.ts) files. It seems like ts-loader is not excl ...

What is the most appropriate form to use, and what factors should be considered in determining

Incorporating generics in typescript allows me to create a generic function in the following manner: Choice 1 declare function foo1<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } Alternatively, I have the option to omit the seco ...

Checking the functionality of a feature with Jasmine framework in an Angular application

I am working on writing unit test cases and achieving code coverage for the code snippet below. Any advice on how to proceed? itemClick($event: any) { for (let obj of this.tocFiles) { let results = this.getchildren(obj, label); if (results) { conso ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

Ensuring type safety at runtime in TypeScript

While delving into the concept of type safety in Typescript, I encountered an interesting scenario involving the following function: function test(x: number){ console.log(typeof x); } When calling this method as test('1'), a compile time er ...

Steps for initiating an Angular 4 project

While most developers have moved on to Angular 5, I was tasked with creating a project using Angular 4. After conducting research for several days, I discovered that downgrading the Angular CLI would allow me to accomplish this. By following this approach, ...

Why won't my code work with a jQuery selector?

I'm struggling to retrieve the value from a dynamically generated <div> using jQuery. It seems like the syntax I'm using doesn't recognize the div with an id tag. The HTML code is stored in a variable, and below is a snippet of code w ...

An individual page application built with Next.js and React requires unique URLs for every item

I recently created a single-page application using Next JS, React JS, and Tailwind CSS to load various items from Firebase. One of the challenges I am facing is allowing users to reference a specific item from the URL and easily share it with others ...

The reason why hydration didn't work was due to the initial UI not being compatible with nextjs specifically on the

Upon opening my current project this morning and running it on the dev server in Chrome, I encountered the following error: "Error: Hydration failed because the initial UI does not match what was rendered on the server." Despite trying various solutions fr ...

Dealing with circular dependencies in NestJS by using ForwardRef

Hey everyone, I've been running into a circular dependency issue with NestJS. I tried using the forwardref method, but it hasn't resolved the problem for me. // AuthModule @Module({ imports: [ forwardRef(() => UserModule), JwtModule ...

Guide to resolving typescript issue 'name' is not found in type 'ByRoleOptions' while accessing by name using getByRole in react-testing-library

I have a custom component that showcases a collection of filters in the form of removable chips. To test this functionality, I am utilizing react-testing-library with a focus on querying by accessible name as outlined here, using the getByRole method. The ...

Combine observables from an id using rxjs in Angular with Firestore

In my Firestore database, I have stored information about people and their pets. Each pet is linked to its owner through an owner ID. // Collection / DocumentID: {data} persons / 'person1': { name: 'Romea' } persons / 'person2&ap ...

Configuring the autoconfig.url in Python using Selenium

Is there a way to set AutoConfigUrl in Python similar to how it is done in Java? Proxy proxy = new Proxy(); proxy.setProxyAutoconfigUrl("http://wpad/wpad.dat"); ...

Secure higher order React component above class components and stateless functional components

I have been working on creating a higher order component to verify the authentication status of a user. Currently, I am using React 15.5.4 and @types/react 15.0.21, and below is a simplified version of my code: import * as React from 'react'; i ...

Enhancing Next.js SEO with 'use client' Metadata

Currently, I am facing an issue with my product page. The metadata for this page is fetched from the backend using an API that retrieves data from a database. To fetch this data and update it on the client side, I am utilizing a custom hook. However, the p ...

An issue has been identified with React's HTML input maxLength feature where it does not display an error

Within my form, I have an input field that currently does not include validation for a maximum length. <input type="text" className="form-control" id="company" onBlur= ...