admin管理员组

文章数量:1122846

I implemented the following function in my Firebase with Cloud Functions backend. Becasue, I want to be able to have my Twitch API token in an environment variable, because the frontend is pure HTML and JavaScript with no Node whatsoever.

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as cors from 'cors';

admin.initializeApp();
const db = admin.firestore();
const corsHandler = cors({ origin: true });

import fetch from 'node-fetch';
export const twitchStatus = functions.https.onRequest(async (req, res) => {
  corsHandler(req, res, async () => {
    // const origin = req.get('origin') || req.get('referer');
    // if (origin !== allowedOrigin) {
    //   res.status(403).json({ error: "Access forbidden, Invalid origin" });
    //   return;
    // }

    try {
      const { channelName } = req.body;

      const url = `=${channelName}`;
      const clientId = process.env.TWITCH_CLIENT_ID as string;
      const accessToken = process.env.TWITCH_ACCESS_TOKEN as string;
  
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Client-ID': clientId,
          'Authorization': `Bearer ${accessToken}`
        }
      });
      const data = await response.json();

      res.status(201).json({ message: "Twitch status created successfully", data: data});
    } catch (error) {
      res.status(500).json({ error: "An error occurred while creating the twitch status." });
    }
  });
});

When trying to deploy, I get the following error:

i  functions: updating Node.js 18 (2nd Gen) function twitchStatus(us-central1)...
Could not create or update Cloud Run service twitchstatus, Container Healthcheck failed. Revision 'twitchstatus-00001-rej' is not ready and cannot serve traffic. The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable within the allocated timeout. This can happen when the container port is misconfigured or if the timeout is too short. The health check timeout can be extended. Logs for this revision might contain more information.

Logs URL: ---
For more troubleshooting guidance, see 

Functions deploy had errors with the following functions:
        twitchStatus(us-central1)
i  functions: cleaning up build files...
!  functions: Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at ---

I have four more similar functions that deploy as expected without errors.

What is going wrong here?

I implemented the following function in my Firebase with Cloud Functions backend. Becasue, I want to be able to have my Twitch API token in an environment variable, because the frontend is pure HTML and JavaScript with no Node whatsoever.

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as cors from 'cors';

admin.initializeApp();
const db = admin.firestore();
const corsHandler = cors({ origin: true });

import fetch from 'node-fetch';
export const twitchStatus = functions.https.onRequest(async (req, res) => {
  corsHandler(req, res, async () => {
    // const origin = req.get('origin') || req.get('referer');
    // if (origin !== allowedOrigin) {
    //   res.status(403).json({ error: "Access forbidden, Invalid origin" });
    //   return;
    // }

    try {
      const { channelName } = req.body;

      const url = `https://api.twitch.tv/helix/streams?user_login=${channelName}`;
      const clientId = process.env.TWITCH_CLIENT_ID as string;
      const accessToken = process.env.TWITCH_ACCESS_TOKEN as string;
  
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Client-ID': clientId,
          'Authorization': `Bearer ${accessToken}`
        }
      });
      const data = await response.json();

      res.status(201).json({ message: "Twitch status created successfully", data: data});
    } catch (error) {
      res.status(500).json({ error: "An error occurred while creating the twitch status." });
    }
  });
});

When trying to deploy, I get the following error:

i  functions: updating Node.js 18 (2nd Gen) function twitchStatus(us-central1)...
Could not create or update Cloud Run service twitchstatus, Container Healthcheck failed. Revision 'twitchstatus-00001-rej' is not ready and cannot serve traffic. The user-provided container failed to start and listen on the port defined provided by the PORT=8080 environment variable within the allocated timeout. This can happen when the container port is misconfigured or if the timeout is too short. The health check timeout can be extended. Logs for this revision might contain more information.

Logs URL: ---
For more troubleshooting guidance, see https://cloud.google.com/run/docs/troubleshooting#container-failed-to-start

Functions deploy had errors with the following functions:
        twitchStatus(us-central1)
i  functions: cleaning up build files...
!  functions: Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at ---

I have four more similar functions that deploy as expected without errors.

What is going wrong here?

Share Improve this question asked Nov 21, 2024 at 9:46 JuanJuan 1 1
  • The code as you've written it above has been written in the style of a V1 Cloud Function, but it is trying to deploy it as a V2 Cloud Function. This is because import * as functions from "firebase-functions" now pulls in the V2 API by default in newer versions of the Firebase Functions SDK. If you want to continue using the V1 syntax, you need to explicitly tell it to use the old API: import * as functions from "firebase-functions/v1". Check the provided troubleshooting link in your error message if you continue to get errors. – samthecodingman Commented Nov 24, 2024 at 23:52
Add a comment  | 

1 Answer 1

Reset to default 0

Have you tried deploying the function with --debug? For example:

firebase deploy --only functions:twitchStatus --debug

Looking at your logs here: functions: updating Node.js 18 (2nd Gen) function twitchStatus(us-central1).... It looks like you have already deployed this function before. Going off your code you are using 1st Gen of cloud functions but the logs say you are updating a 2nd Gen function. You can find out more here about upgrading. I would go into your firebase dashboard > functions and delete that function and attempt to redeploy again.

Few other notes:

You should also look at the firebase docs about configuring your environment. You can store your secrets in Google Secret Manager. This can all be done via the Firebase cli. For example:

firebase functions:secrets:set TWITCH_ACCESS_TOKEN

Once you have entered your secret value you will then need grant that function access. Below is an example:

const { defineSecret } = require('firebase-functions/params');
const twitchAccessTkn = defineSecret('TWITCH_ACCESS_TOKEN');

const { onRequest } = require('firebase-functions/v2/https');

export const postToDiscord = onRequest({ secrets: [twitchAccessTkn] },
  (req, res) => {
    const accessTkn = twitchAccessTkn.value(); // access it here!

For your fetch request you also need to handle the exceptions better. You can read more about it here, but the main idea is that you need to check response.ok. For example:

if (!response.ok) {
      const error = await response.json();
      logger.error(`twitchStatus`, error); // log it!
      throw new Error(error.message ?? "Error!"); // throw the error
    }

本文标签: