Search code examples
javascriptnode.jsnext.jsmqttapp-router

Nextjs App Route api giving initial data on run build, normally in run dev


I have a Next.js page with App Router. The page get the data from it's route API. Data obtained from MQTT. In development (run dev), when we send request to api/getLocation it will return updated data from MQTT. But in production, data returned was initial data (not updated from MQTT). I can't figure where is the mistakes

This is route file on handling user data request "app/api/realtimeLocation/route.ts

import mqttSubscriber from './mqtt-subscriber'

export async function GET(req: any, res: any) {
   const { data } = mqttSubscriber
   let validateData = data ? JSON.parse(data) : null
   try {
      return Response.json({
         status: 'OK',
         data: validateData
      })
   } catch (err) {
      console.error('Something wrong happen')
   }
}

and it's my mqtt configure "mqtt-subscriber.js" in same directory

import * as mqtt from 'mqtt'

const client = mqtt.connect(`mqtt://${process.env.NEXT_PUBLIC_IP_MQTT}:1883`, {
   username: 'my-user',
   password: 'my-password',
})
// subscribe
client.on('connect', () => {
   const topic = 'fms/liveLocations'
   // subscrive
   client.subscribe(topic, err => {
      if (err) {
         console.log(err)
      } else {
         console.log(`Subscribe to topic: ${topic}`)
      }
   })
})
client.on('error', err => console.log('MQTT Error: ', err))
const receivedData = { data: null }
client.on('message', (receivedTopic, message) => {
   receivedData.data = message.toString()
})

export default receivedData

Solution

  • can you try adding this line at the top of your route.ts?

    export const dynamic = "force-dynamic";
    

    I am not familiar with MQTT's behavior, but my guess is your data is cached by NextJS, and thus serving the static initial data that is retrieved on build time (afterwards every request will return the same data cached).

    By adding the "force-dynamic" tag, it tells NextJS to evaluate the route on run time.

    On another hand, I am guessing that your code works in dev mode because of different caching strategy