Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

node.js - Next.js - serving images from GridFS

I'm looking to serve some images I have stored in my GridFS database to my Next.js project. Sometimes the images load in development (sometimes they don't), however they never load in production. I'm using gridfs-stream to serve the images.

On the client side the image is called like this:

<img src={`/api/image?id=${filename}`} />

And on the server it serves the image like this:

import mongoose from 'mongoose';
import nc from 'next-connect';

const Grid = require('gridfs-stream');
const conn = mongoose.createConnection(gridFSURI);

let gfs;
conn.once('open', () => {
  gfs = Grid(conn.db, mongoose.mongo);

const handler = nc();

handler.get((req, res) => {
  gfs.files.findOne({ filename: req.query.id }, (err, file) => {
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: 'No file exists'
    } else {
      const readstream = gfs.createReadStream(file.filename);

export const config = {
  api: {
    bodyParser: false,

export default handler;

Should these images be served through getServerSideProps?

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share