Bird
Raised Fist0
Firebasecloud~5 mins

HTTP trigger functions in Firebase - Commands & Configuration

Choose your learning style10 modes available
Introduction
HTTP trigger functions let you run code when someone visits a web address. This helps you respond to web requests like showing a page or processing data without managing servers.
When you want to create a simple web API that responds to user requests.
When you need to run backend code after a user submits a form on your website.
When you want to build a webhook that reacts to events from other services.
When you want to serve dynamic content or data without setting up a full server.
When you want to quickly test backend logic triggered by HTTP calls.
Config File - index.js
index.js
const functions = require('firebase-functions');

exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send('Hello from Firebase HTTP trigger!');
});

This file defines a Firebase Cloud Function named helloWorld that runs when an HTTP request is received.

functions.https.onRequest sets up the HTTP trigger.

The function sends back a simple text response.

Commands
Initialize Firebase Functions in your project folder to set up the environment for writing and deploying functions.
Terminal
firebase init functions
Expected OutputExpected
=== Functions Setup === You're about to initialize a Firebase Functions project. ? What language would you like to use to write Cloud Functions? JavaScript ? Do you want to use ESLint to catch probable bugs and enforce style? No ? Do you want to install dependencies with npm now? Yes ✔ Wrote functions/package.json ✔ Wrote functions/index.js ✔ Wrote functions/.eslintrc.js + Firebase initialization complete!
Deploy your HTTP trigger function to Firebase so it becomes available on the internet.
Terminal
firebase deploy --only functions
Expected OutputExpected
=== Deploying to 'your-project-id'... i deploying functions Running command: npm --prefix "$RESOURCE_DIR" run lint ✔ functions: Finished running predeploy script. ✔ functions[helloWorld]: Successful update operation. ✔ Deploy complete! Project Console: https://console.firebase.google.com/project/your-project-id/overview
→
--only functions - Deploy only the functions part without affecting other Firebase services
Check the logs of your deployed function to see requests and debug messages.
Terminal
firebase functions:log
Expected OutputExpected
2024-06-01T12:00:00.000Z helloWorld: Function execution started 2024-06-01T12:00:00.100Z helloWorld: Function execution finished
Send an HTTP request to your deployed function URL to test that it responds correctly.
Terminal
curl https://us-central1-your-project-id.cloudfunctions.net/helloWorld
Expected OutputExpected
Hello from Firebase HTTP trigger!
Key Concept

If you remember nothing else from this pattern, remember: HTTP trigger functions run your code whenever someone visits a special web address you create.

Common Mistakes
Not deploying the function after writing or changing the code
The function won't update on Firebase, so your changes won't take effect.
Always run 'firebase deploy --only functions' after editing your function code.
Calling the function URL before deployment finishes
The function URL won't work yet and will return an error or 404.
Wait for the deploy command to complete successfully before testing the URL.
Not initializing Firebase Functions in the project folder
You won't have the necessary files and setup to write or deploy functions.
Run 'firebase init functions' once before creating your first function.
Summary
Initialize Firebase Functions in your project with 'firebase init functions'.
Write your HTTP trigger function in 'index.js' using 'functions.https.onRequest'.
Deploy your function with 'firebase deploy --only functions' to make it live.
Test your function by sending an HTTP request to its URL or using curl.
Check logs with 'firebase functions:log' to monitor function activity.

Practice

(1/5)
1. What does an HTTP trigger function in Firebase do?
easy
A. Automatically updates the database without user input
B. Runs code when a specific web URL is visited
C. Sends emails to users without any request
D. Creates a new Firebase project

Solution

  1. Step 1: Understand HTTP trigger functions

    HTTP trigger functions run when someone visits a specific web address (URL).
  2. Step 2: Compare options with this behavior

    Only Runs code when a specific web URL is visited describes running code on visiting a URL, matching the definition.
  3. Final Answer:

    Runs code when a specific web URL is visited -> Option B
  4. Quick Check:

    HTTP trigger = run code on URL visit [OK]
Hint: HTTP trigger = runs code on web URL visit [OK]
Common Mistakes:
  • Confusing HTTP triggers with database triggers
  • Thinking HTTP triggers run automatically without requests
  • Assuming HTTP triggers send emails by default
2. Which of the following is the correct way to define an HTTP trigger function in Firebase using Node.js?
easy
A. exports.myFunc = functions.storage.object().onFinalize((object) => { });
B. exports.myFunc = functions.database.onWrite((change, context) => { });
C. exports.myFunc = functions.https.onRequest((req, res) => { res.send('Hello'); });
D. exports.myFunc = functions.auth.user().onCreate((user) => { });

Solution

  1. Step 1: Identify HTTP trigger syntax

    HTTP triggers use functions.https.onRequest with (req, res) parameters.
  2. Step 2: Match options to this syntax

    Only exports.myFunc = functions.https.onRequest((req, res) => { res.send('Hello'); }); uses functions.https.onRequest correctly; others are for database, auth, or storage triggers.
  3. Final Answer:

    exports.myFunc = functions.https.onRequest((req, res) => { res.send('Hello'); }); -> Option C
  4. Quick Check:

    HTTP trigger uses functions.https.onRequest [OK]
Hint: HTTP triggers use functions.https.onRequest syntax [OK]
Common Mistakes:
  • Using database or auth triggers instead of HTTP triggers
  • Missing (req, res) parameters in function
  • Confusing storage triggers with HTTP triggers
3. What will be the output when visiting the URL of this Firebase HTTP function?
exports.greet = functions.https.onRequest((req, res) => { const name = req.query.name || 'Guest'; res.send(`Hello, ${name}!`); });

URL visited: https://us-central1-project.cloudfunctions.net/greet?name=Alice
medium
A. Hello, Alice!
B. Hello, Guest!
C. Hello, undefined!
D. Error: name not found

Solution

  1. Step 1: Understand query parameter usage

    The function reads the 'name' from the URL query string; if missing, it uses 'Guest'.
  2. Step 2: Check the URL query

    The URL has '?name=Alice', so name = 'Alice'. The response is 'Hello, Alice!'.
  3. Final Answer:

    Hello, Alice! -> Option A
  4. Quick Check:

    Query name=Alice -> Hello, Alice! [OK]
Hint: Query params fill variables; missing uses default [OK]
Common Mistakes:
  • Ignoring query parameters and using default always
  • Assuming undefined if parameter missing
  • Expecting error instead of default value
4. Identify the error in this Firebase HTTP trigger function:
exports.testFunc = functions.https.onRequest((request, response) => { response.send('Test'); response.send('Done'); });
medium
A. Incorrect parameter names for the function
B. Missing return statement after response.send()
C. No error, function works fine
D. Calling response.send() twice causes an error

Solution

  1. Step 1: Check response.send() usage

    response.send() ends the HTTP response. Calling it twice causes an error.
  2. Step 2: Analyze the code flow

    The function calls response.send('Test') then immediately calls response.send('Done'), which is invalid.
  3. Final Answer:

    Calling response.send() twice causes an error -> Option D
  4. Quick Check:

    Only one response.send() allowed per request [OK]
Hint: Use response.send() only once per HTTP request [OK]
Common Mistakes:
  • Calling response.send() multiple times
  • Thinking parameter names must be req, res exactly
  • Ignoring that response ends after send
5. You want to create an HTTP trigger function that accepts a JSON body with a field age and responds with {"canVote": true} if age is 18 or more, otherwise {"canVote": false}. Which code snippet correctly implements this?
hard
A. exports.checkVote = functions.https.onRequest((req, res) => { const age = req.body.age; if(age >= 18) { res.json({canVote: true}); } else { res.json({canVote: false}); } });
B. exports.checkVote = functions.https.onRequest((req, res) => { const age = req.query.age; if(age > 18) { res.send({canVote: true}); } else { res.send({canVote: false}); } });
C. exports.checkVote = functions.https.onRequest((req, res) => { const age = req.body.age; if(age > 18) { res.send('{"canVote": true}'); } else { res.send('{"canVote": false}'); } });
D. exports.checkVote = functions.https.onRequest((req, res) => { const age = req.body.age; if(age > 18) { res.send({canVote: true}); } else { res.send({canVote: false}); } });

Solution

  1. Step 1: Identify correct data source and response method

    The age is sent in JSON body, so use req.body.age. To send JSON response, use res.json().
  2. Step 2: Check conditions and response format

    exports.checkVote = functions.https.onRequest((req, res) => { const age = req.body.age; if(age >= 18) { res.json({canVote: true}); } else { res.json({canVote: false}); } }); correctly checks age >= 18 and sends JSON object with canVote true or false using res.json().
  3. Final Answer:

    exports.checkVote = functions.https.onRequest((req, res) => { const age = req.body.age; if(age >= 18) { res.json({canVote: true}); } else { res.json({canVote: false}); } }); -> Option A
  4. Quick Check:

    Use req.body and res.json() for JSON input/output [OK]
Hint: Use req.body for JSON input and res.json() to respond [OK]
Common Mistakes:
  • Using req.query instead of req.body for JSON data
  • Sending JSON as string instead of object
  • Using res.send() with object without res.json()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard