H
Hono4d ago
DennisK

Migrating from Express to Hono. Static files caching

Hi! Migrating from Express and I do have a hard time understanding how caching works in Hono. In Express we could do this:
app.use(
'/assets',
express.static('build/client/assets', { immutable: true, maxAge: '1y' }),
)

app.use(express.static('build/client', { maxAge: '1h' }))
app.use(
'/assets',
express.static('build/client/assets', { immutable: true, maxAge: '1y' }),
)

app.use(express.static('build/client', { maxAge: '1h' }))
And I want to get the exact same result. I came up with this:
server.use(
"/assets/*",
serveStatic({
root: "./build/client/assets",
getContent: async (filePath) => {
const resolvedPath = path.join(
process.cwd(),
"./build/client/assets",
filePath
)
try {
const data = await fs.readFile(resolvedPath)
const response = new Response(data)
// Set long-term caching: 1 year (31536000 seconds), immutable
response.headers.set(
"Cache-Control",
"public, max-age=31536000, immutable"
)
return response
} catch {
return null // If file not found, proceed to next middleware
}
},
})
)

// Serve static files from 'build/client' for all other paths
server.use(
"/*",
serveStatic({
root: "./build/client",
getContent: async (filePath, c) => {
const resolvedPath = path.join(
process.cwd(),
"./build/client",
filePath
)
try {
const data = await fs.readFile(resolvedPath)
const response = new Response(data)
// Set short-term caching: 1 hour (3600 seconds)
response.headers.set("Cache-Control", "public, max-age=3600")
return response
} catch {
return null // If file not found, proceed to next middleware
}
},
})
)
server.use(
"/assets/*",
serveStatic({
root: "./build/client/assets",
getContent: async (filePath) => {
const resolvedPath = path.join(
process.cwd(),
"./build/client/assets",
filePath
)
try {
const data = await fs.readFile(resolvedPath)
const response = new Response(data)
// Set long-term caching: 1 year (31536000 seconds), immutable
response.headers.set(
"Cache-Control",
"public, max-age=31536000, immutable"
)
return response
} catch {
return null // If file not found, proceed to next middleware
}
},
})
)

// Serve static files from 'build/client' for all other paths
server.use(
"/*",
serveStatic({
root: "./build/client",
getContent: async (filePath, c) => {
const resolvedPath = path.join(
process.cwd(),
"./build/client",
filePath
)
try {
const data = await fs.readFile(resolvedPath)
const response = new Response(data)
// Set short-term caching: 1 hour (3600 seconds)
response.headers.set("Cache-Control", "public, max-age=3600")
return response
} catch {
return null // If file not found, proceed to next middleware
}
},
})
)
Does this looks ok or is there a better/more performant way of doing it?
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?