Last active
March 29, 2025 13:28
-
-
Save raditotev/7bef90a0a6ec37a18cfa9aa9b3655a45 to your computer and use it in GitHub Desktop.
Uploading files to Firebase/ Storage using Nodejs, express and multer with memoryStorage as storage option
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const morgan = require('morgan'); | |
const cors = require('cors'); | |
const createError = require('http-errors'); | |
const bodyParser = require('body-parser'); | |
const { initializeApp } = require('firebase/app'); | |
const { | |
getStorage, | |
ref, | |
uploadBytes, | |
getDownloadURL, | |
} = require('firebase/storage'); | |
const multer = require('multer'); | |
const app = express(); | |
// Firestore setup | |
const { API_KEY, AUTH_DOMAIN, PROJECT_ID, BUCKET, SENDER_ID, APP_ID } = | |
process.env; | |
const firebaseConfig = { | |
apiKey: API_KEY, | |
authDomain: AUTH_DOMAIN, | |
projectId: PROJECT_ID, | |
storageBucket: BUCKET, | |
messagingSenderId: SENDER_ID, | |
appId: APP_ID, | |
}; | |
const firebaseApp = initializeApp(firebaseConfig); | |
const firestore = getStorage(firebaseApp); | |
// Multer setup | |
const storage = multer.memoryStorage(); | |
const upload = multer({ storage }); | |
// Middleware | |
app.use(morgan('dev')); | |
app.use(bodyParser.urlencoded({ extended: false })); | |
app.use(bodyParser.json()); | |
app.use(cors()); | |
// Routes | |
app.post('/products', upload.single('image'), async (req, res, next) => { | |
const file = req.file; | |
try { | |
const filename = new Date().getTime() + '-' + file.originalname; | |
const imageRef = ref(firestore, 'products/' + filename); | |
const snapshot = await uploadBytes(imageRef, file.buffer); | |
const imageURL = await getDownloadURL(snapshot.ref); | |
res.status(200).send(imageURL); | |
} catch (error) { | |
return next(createError(502, error.message)); | |
} | |
}); | |
// Non existing routes | |
app.use((req, res, next) => { | |
const error = new createError.NotFound(); | |
next(error); | |
}); | |
// Error handling | |
app.use((error, req, res, next) => { | |
res | |
.status(error.status || 500) | |
.json({ message: error.message || 'Server error' }); | |
}); | |
app.listen(process.env.PORT || 3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment