Skip to content

Commit

Permalink
Add staticFileMiddleware.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
whaaaley committed Nov 24, 2024
1 parent 4aa5c85 commit 37bd870
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
4 changes: 4 additions & 0 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@ app.use(middleware.errorMiddleware)
app.use(middleware.loggerMiddleware)
app.use(middleware.corsMiddleware)

app.use(middleware.staticFileMiddleware)

app.use(routes.api.routes())
app.use(routes.api.allowedMethods())

// This middleware should be the last one to handle SPA routing in case the
// requested file does not exist
app.use(middleware.spaRoutingMiddleware)

const port = parseInt(env.PORT ?? '3000')
Expand Down
1 change: 1 addition & 0 deletions server/middleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export { corsMiddleware } from './corsMiddleware.ts'
export { errorMiddleware } from './errorMiddleware.ts'
export { loggerMiddleware } from './loggerMiddleware.ts'
export { spaRoutingMiddleware } from './spaRoutingMiddleware.ts'
export { staticFileMiddleware } from './staticFileMiddleware.ts'
20 changes: 20 additions & 0 deletions server/middleware/staticFileMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Context, Next, send } from '@oak/oak'

// Middleware to handle static file requests
export const staticFileMiddleware = async (ctx: Context, next: Next) => {
const { request, response } = ctx
const path = request.url.pathname

if (path.startsWith('/assets')) {
try {
await send(ctx, path, {
root: './dist',
})
} catch (error) {
response.status = error.status ?? 500
response.body = error.message ?? 'Internal Server Error'
}
} else {
await next()
}
}

0 comments on commit 37bd870

Please sign in to comment.