Skip to content

Node.js Express.js Server Starter Template. Helps to developer setup the Backend Server within few seconds.

Notifications You must be signed in to change notification settings

smmunna/node-server-starter

Repository files navigation

Node-Express Server Starter Template

Installation Process

  1. Run the following command
npx node-expressx
  1. Create a new database in MongoDB Compass or MongoDB Cloud Storage

  2. Then update name example.env to .env. Goto this .env file DATABASE_URL, Default name given nextjs change it whatever you want.

  3. You can add local and also cloud for production level.

  4. Then create a new table name users, contain following fields.

    {
       "username": "",
       "email": "",
       "password": "",
       "role": ""
    }

    You can open postman and paste this api endpoint into the url section

       http://localhost:5000/api/v1/users

    After that select body and also json as format and paste that object, used bcrypt to encrypt password

    {
      "username": "Minhazul Abedin Munna",
      "email": "[email protected]",
      "password": "1234",
      "role": "admin"
    }

    Now select POST method and hit send button, It will successfully create a user.

  5. Goto this project directory & open terminal

npm run start:dev
  1. Now project will run in following port
http://localhost:5000

API Endpoints

http://localhost:5000/api/v1/
http://localhost:5000/api/v1/users

Instructions

  1. Create any module by this command
npm run create-module moduleName

Deleting a Module by following this command

npm run delete-module moduleName
  1. If you want to delete any module , just delete the module form src/app/modules/moduleName and also delete the route from src/app/routes/index.ts file.

Deploy

  1. Just run the following command, This will generate the dist directory. Which you can deploy to the server.
npm run build
  1. After getting the dist directory, you can run the following command
npm run start:prod

You can check whether your project is working perfectly for the production level or not.

Features

  1. File upload configured with Multer, cloudinary, imgbb
  2. Payment gateway configured with sslcommerze, paypal & stripe
  3. Organized file with modular approach (controller, service, route, interface)
  4. Socket.io configured for real time communication
  5. MongoDB configured
  6. Mail Server configured with Node Mailer
  7. Query Builder configured

File Uploading Process

  1. Make a route this way:
import multer from 'multer';
// File uploading configuration..
const upload = multer()

router.post('/up/file', upload.single('photo'), userController.testUpload); //single file upload
router.post('/up/file', upload.array('photo'), userController.testUpload); //multiple file upload
router.post('/up/file', upload.array('photo',10), userController.testUpload); //specific limit file upload
  1. Controller methods will be this way:
const testUpload = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const file = req.file as Express.Multer.File;

    if (!file) {
      return res.status(400).json({ message: 'No file uploaded' });
    }

    // Check file size condition first before proceeding with upload
    if (file.size > 10 * 1024) { // 10KB = 10 * 1024 bytes
      return res.status(400).json({ message: `File ${file.originalname} exceeds 10KB, cannot be uploaded` });
    }

    // Check file type (only jpg and png are allowed)
    const allowedMimes = ['image/jpeg', 'image/png'];
    if (!allowedMimes.includes(file.mimetype)) {
      return res.status(400).json({ message: `Invalid file type. Only JPG and PNG files are allowed.` });
    }

    // Save the file and get its URL
    const folderPath = 'absk/ads';
    let fileURL: string;
    try {
      fileURL = saveFile(file.buffer, file.originalname, folderPath, req);
    } catch (error: any) {
      return res.status(500).json({
        message: `Failed to upload file ${file.originalname}: ${error.message}`,
      });
    }

    // Respond with success message if file is uploaded successfully
    res.json({
      message: 'File uploaded successfully',
      fileURL,
    });

  } catch (error) {
    next(error); // Pass any errors to the error-handling middleware
  }

};
  1. For uploading multiple files, then follow this process
try {
    const files = req.files as Express.Multer.File[];

    if (!files || files.length === 0) {
      return res.status(400).json({ message: 'No files uploaded' });
    }

    // Check file size condition first before proceeding with uploads
    const errors: string[] = [];

    // Check each file
    for (const file of files) {
      if (file.size > 10 * 1024) { // 10KB = 10 * 1024 bytes
        errors.push(`File ${file.originalname} exceeds 10KB, cannot be uploaded`);
      }
    }

    // If there are any errors, reject the upload and don't save any files
    if (errors.length > 0) {
      return res.status(400).json({
        message: 'Some files failed to upload',
        errors,
      });
    }

    // Array to store the URLs of successfully uploaded files
    const fileURLs: string[] = [];

    // If all files pass the size condition, proceed with the upload
    for (const file of files) {
      // Save the file and get its URL
      const folderPath = 'uploads/photos';
      try {
        const fileURL = saveFile(file.buffer, file.originalname, folderPath, req);
        fileURLs.push(fileURL);
      } catch (error: any) {
        errors.push(`Failed to upload file ${file.originalname}: ${error.message}`);
      }
    }

    // If there are still errors, return them
    if (errors.length > 0) {
      return res.status(400).json({
        message: 'Some files failed to upload',
        errors,
      });
    }

    // Respond with success message if all files were uploaded successfully
    res.json({
      message: 'Files uploaded successfully',
      fileURLs,
    });

  } catch (error) {
    next(error); // Pass any errors to the error-handling middleware
  }
  1. Mime types are available
const allowedMimes = [
  // Image MIME types
  'image/jpeg',    // JPG
  'image/png',     // PNG
  'image/gif',     // GIF
  'image/webp',    // WEBP
  'image/bmp',     // BMP
  'image/svg+xml', // SVG
  
  // Document MIME types
  'application/pdf',    // PDF
  'application/msword', // DOC
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // DOCX
  'application/vnd.ms-powerpoint', // PPT
  'application/vnd.openxmlformats-officedocument.presentationml.presentation', // PPTX
  'application/vnd.ms-excel', // XLS
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // XLSX
  'text/plain', // TXT
  'text/csv',   // CSV
  'application/rtf',  // RTF
  
  // Audio MIME types
  'audio/mpeg',   // MP3
  'audio/wav',    // WAV
  'audio/ogg',    // OGG
  'audio/mp4',    // MP4 audio
  'audio/aac',    // AAC
  
  // Video MIME types
  'video/mp4',    // MP4
  'video/x-msvideo', // AVI
  'video/ogg',    // OGG video
  'video/webm',   // WebM
  'video/mkv',    // MKV
  
  // Archive/Compressed file MIME types
  'application/zip',      // ZIP
  'application/x-zip-compressed', // ZIP (another type)
  'application/x-rar-compressed', // RAR
  'application/x-tar',     // TAR
  'application/gzip',     // GZ
  'application/x-7z-compressed' // 7Z
];

if (!allowedMimes.includes(file.mimetype)) {
  return res.status(400).json({
    message: `Invalid file type. Allowed types are: ${allowedMimes.join(', ')}`
  });
}
  1. Deleting the file
// File Deleting
const deleteFileData = async (req: Request, res: Response) => {
  /*
    When you want to delete any product or delete any user information with their photo or other files.
    This deleting method will help you.
    Just fetch the data from database then you will get photo url. just pass this url to parsedURL() method, then
    deleteFastFile() will delete the file
    */
  // ===============DELETE LOCAL FILE============
  const path = 'http://localhost:5000/uploads/user-1728138253071.png'
  const urlconversion = parsedURL(path) // convert into uploads/user-1728138253071.png like this
  if (urlconversion) {
      deleteFastFile(urlconversion) // takes the file path as parameter, uploads/user-3843.png and delete it.
      sendApiResponse(res, 200, true, 'Deleted file successfully')
  }
  else {
      console.log('Not Deleted, Try again later')
  }
  // ===============END OF DELETING LOCAL FILE============
};

Contributor ✨


Minhazul Abedin Munna

Thank you

2024-2025© Developed by smmunna