Wednesday, 20 September 2023

Streaming mp4 video (mongodb gridfsbucket) in nextJS application

I'm trying to stream a mp4 video file in my nextJS application. The file is stored in a mongodb GridFSBucket.

So, for this I'm using getServerSideProps(). Calling the page in chrome browser shows up a video player, but the video isn't playing (duration 0:00). I do see multiple log messages warn - You should not access 'res' after getServerSideProps resolves.. But I don't think that is the issue as it is only a warning.

Maybe someone can see a fundamental error in my code as I don't have clue how to debug the issue without any error messages.

[hash].tsx

export const getServerSideProps: GetServerSideProps = async ({
    res,
    query: { hash }
}) => {        
    const database = await mongodb()
    const Videos = database.collection('videos')

    const { fileId } = await Videos.findOne({ uid: hash })

    const Files = new GridFSBucket(database)
    const id = new ObjectId(fileId)

    const file: GridFSFile = await new Promise((resolve, reject) => {
        Files.find({
            _id: id
        }).toArray((err, files) => {
            if (err) reject(err)
            resolve(files[0])
        })
    })
    const { contentType } = file || {}

    res.writeHead('Content-Type', contentType) // contentType is "video/mp4"
    Files.openDownloadStream(id)
    .on('data', (chunk) => {
        res.write(chunk)
    })
    .on('end', () => {
        res.end()
    })
    .on('error', (err) => {
        throw err
    })

    return {
        props: {}
    }
}


from Streaming mp4 video (mongodb gridfsbucket) in nextJS application

No comments:

Post a Comment