Using multer in next.js routes with typescript

Hello everyone, I have to upload an array of images to mongo.db. I assume the best way is to use multer-grid-fs-storage. The store is done, now I only need to implement the upload function in my POST function. After research I tried it now with next-connect, but typescript tells me that the nc() function is not callable.
code:

import upload from "../utils/multer";
import * as nc from 'next-connect';
//Create
// const handler = nc<NextApiRequest, NextApiResponse>();
const POST = nc().use(upload.array('images')).post(async (request: NextApiRequest, response: NextApiResponse) => {
  try {
    await connect();
    const data = request.body;
    const newBlogPost = new BlogPost(data);
    await newBlogPost.save();
    return new NextResponse(JSON.stringify(newBlogPost), { status: 201 });
  } catch (error) {
    return new NextResponse("Fehler beim Erstellen des BlogPosts", { status: 403 });
  }
});

Thanks for your help

look for their typed script version for this library, that might be it, happy coding :slight_smile:

I don’t see it being imported and used in the docs the way you are doing it. You probably also need to use the expressWrapper with Multer (considering it is middleware).


If you look at the source, you can see they are named exports.

https://github.com/hoangvvo/next-connect/blob/main/src/index.ts

So if you do import * as fn from 'somePackage' you get an object with the named exports, not a function.

I found now some workaround, but compared to node, where I only have to write the upload function into the route, it is a bit complicated. So perhaps I will find a better solution in the future. That is my current code:

import upload from "../utils/multer";
import { Express } from 'express';

interface MulterFile {
  fieldname: string;
  originalname: string;
  encoding: string;
  mimetype: string;
  size: number;
  destination: string;
  filename: string;
  path: string;
  buffer: Buffer;
}

interface MulterRequest extends NextApiRequest {
  files: MulterFile[];
}

let uploader = upload.array('images');

const POST = async (request: NextApiRequest, response: NextApiResponse) => {
  try {
    await connect();
    uploader(request as any, response as any, async function (err) {
      if (err) {
        return new NextResponse("Fehler beim Hochladen der Bilder", { status: 400 });
      }
      const data = (request as MulterRequest).body;
      data.images = (request as MulterRequest).files.map(file => file.filename);
      const newBlogPost = new BlogPost(data);
      await newBlogPost.save();
      return new NextResponse(JSON.stringify(newBlogPost), { status: 201 });
    });
  } catch (error) {
    return new NextResponse("Fehler beim Erstellen des BlogPosts", { status: 400 });
  }
};

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.