Send file as response using NextJS API
Answering my own question here for those who're curious to know too..
I made a thread about it in NextJS and they gave me a good answer to this - here
2 ways of doing this is either by using readStream
var filePath = path.join(__dirname, 'myfile.mp3'); var stat = fileSystem.statSync(filePath); response.writeHead(200, { 'Content-Type': 'audio/mpeg', 'Content-Length': stat.size }); var readStream = fileSystem.createReadStream(filePath); // We replaced all the event handlers with a simple call to readStream.pipe() readStream.pipe(response);
or change the object into buffer and use send method
/*Project structure:.├── images_folder│ └── next.jpg├── package.json├── pages│ ├── api│ │ └── image.js│ └── index.js├── README.md└── yarn.lock*/// pages/api/image.jsimport fs from 'fs'import path from 'path'const filePath = path.resolve('.', 'images_folder/next.jpg')const imageBuffer = fs.readFileSync(filePath)export default function(req, res) { res.setHeader('Content-Type', 'image/jpg') res.send(imageBuffer)}
Both answers work in my case. Use process.cwd()
to navigate to the files / image that needed to be send as response.