I'm building an api using express netlify-lambda and firebase, but stumbled into this error. When I visit the url to get the data I get a ReferenceError: Headers is not defined. So I've figured out it was a problem with firebase, but I couldn't find the correct information I was looking for.
So this is what I'm trying to do, here are my imports:
const express = require('express');
const serverless = require('serverless-http');
const firebase = require("../resources/firebase"); // Import firebase config file
const bodyParser = require('body-parser');
const {doc, getDoc } = require("firebase/firestore");
Here's the part of the router:
const app = express();
const router = express.Router();
router.get('/memes', async (req, res) => {
const apiKey = req.query.key;
const hashedApiKey = hashAPIKey(apiKey)
// This is where i get the error
const customerId = await getDoc(doc(firebase.db, "apiKeys", hashedApiKey));
const customer = await getDoc(doc(firebase.db, "customers", customerId.toString()));
if (!customer.active) {
res.sendStatus(403)
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Hello from Express.js!</h1>');
res.end();
}
});
app.use(bodyParser.json());
app.use('/.netlify/functions/index', router);
module.exports = app;
module.exports.handler = serverless(app);
After running the command to startup netlify-lambda "start": "netlify-lambda serve src" and then visiting this url http://localhost:9000/.netlify/functions/index/memes?key=bla the error will be thrown and netlify-lambda will shutdown.
I'm guessing I need to send headers with a Bearer token to firebase before trying to get a document. I could also be completely wrong. Anyway if anyone knows what to do please tell me. Thanks in advance.
To send headers with a Bearer token to firebase before trying to get a document, Bearer Token must be added to Firebase via the Authorization header. The header is usually formatted as follows:
Authorization: Bearer <token>
This is documented in the OAuth 2.0 Authorization Framework: Bearer Token Usage, section 2.1. Of course, your backend should parse the same format.
Keep in mind that the Headers constructor isn't available in the node.js environment. You'll need to include it from the node-fetch package, just like fetch. To get it from the fetch function, you can use a destructuring assignment.
const fetch = require('node-fetch'); const { Headers } = fetch;
To create a new instance, utilize the property directly.
let headers = new fetch.Headers();
For further information, see the node-fetch documentation.