How to access file uploaded in "public/static" folder from api in BlitzJs and NextJs 12

33 Views Asked by At

I have a website using Blitzjs for the back end and Next.js for the front end. Everything seems to be working fine, but I'm facing an issue with file uploads. When I deploy the back end to production (yarn build - yarn start), I perform an upload from the client side. The file upload is successful, and it exists on the server.

However, it doesn't show on the website, and when I access the link, it gives a 404 error, even though the file is on the server. I've used a custom server for the back end, but it seems like it's still unable to access the file unless I restart the server or run yarn dev. I'm using Blitzjs (2.0.0-beta.26), Next.js (12.1.0), and TypeScript

Below is my code, and I hope someone can help me fix this.

// Import dependencies
const dayjs = require("dayjs")
const utc = require("dayjs/plugin/utc")
const { Server } = require("socket.io")
const { createNotification } = require("src/query/notification")
const { getShopById } = require("src/query/shop")
const { NotificationType } = require("src/types")
const { pushEmailInWeek, pushNotificationAndEmailEvent } = require("utilities/cron-job")

const next = require("next")
const express = require("express")
const cors = require("cors")
const http = require("http")
const cron = require("node-cron")

// Config server
const dev = process.env.NODE_ENV !== "production"
const hostname = "localhost"
const port = 3009

const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()
dayjs.extend(utc)

app.prepare().then(() => {
  // Create HTTP server
  const server = express()
  const httpServer = http.createServer(server)

  // Initialize Socket.io
  const io = new Server(httpServer, {
    cors: { origin: "*" },
  })

  // Use the cors middleware to enable CORS support
  server.use(cors())
  // Config static folder to access files
  server.use(express.static("static"))
  server.use("/static", express.static("public"))
  // Server CORS config
  server.options("*", cors())

  server.all("*", (req, res) => {
    res.header("Access-Control-Allow-Origin", "*")
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS")
    res.header(
      "Access-Control-Allow-Headers",
      "Origin, X-Requested-With, Content-Type, Accept, Authorization"
    )
    return handle(req, res)
  })
  // Socket connection
  io.on("connection", (socket) => {
    console.log("A user connected")

    socket.on("notification-data", async (data) => {
      const { usersId, notificationType, shopId, eventSlug, productSlug, shopSlug } = data
      const shop = await getShopById(shopId)
      const shopName = shop.name
      let slugFeature, title, content

      if (notificationType === NotificationType.AddNewEvent) {
        slugFeature = eventSlug
        title = `${shopName} added an event`
        content = `${shopName} added an event, click to view now`
      } else if (notificationType === NotificationType.AddNewProduct) {
        slugFeature = productSlug
        title = `${shopName} added a new product`
        content = `${shopName} added a new product, click to view now`
      } else if (notificationType === NotificationType.AddNewMedia) {
        slugFeature = shopSlug
        title = `${shopName} added a media`
        content = `${shopName} added a media, click to view now`
      }

      const notificationData = {
        usersIdArr: usersId,
        notificationMessage: title,
      }

      for (const userId of usersId) {
        await createNotification(userId, shopId, notificationType, slugFeature, title, content)
      }

      io.emit("notification-client", notificationData)
    })

    socket.on("disconnect", () => {
      console.log("A user disconnected")
    })
  })

  cron.schedule("*/2 * * * *", async () => {
    // Cron job run at every 2nd minute.
    await pushNotificationAndEmailEvent(io)
  })

  cron.schedule("0 0 * * 6,0", async () => {
    // Cron job run at every weekend.
    await pushEmailInWeek()
  })

  httpServer.listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})
export {}

I've tried configuring it, but it appears that everything remains the same. I hope someone can help me fix this.

0

There are 0 best solutions below