Skip to content

Instantly share code, notes, and snippets.

@hmanicka
Last active November 19, 2018 23:21
Show Gist options
  • Save hmanicka/c6ef757862d03476c2909f1118d87a3d to your computer and use it in GitHub Desktop.
Save hmanicka/c6ef757862d03476c2909f1118d87a3d to your computer and use it in GitHub Desktop.
Serving static assets in expressjs
import express from 'express'
import cors from 'cors'
import morgan from 'morgan'
// import your API routes
const app = express()
const path = require('path')
// Get the path to your static assets somehow...
const rootUrl = process.env.ROOT_URL || '../client/build'
// Serve static files from the React app
const pathToStaticFiles = path.resolve(__dirname, rootUrl)
app.use(express.static(path.resolve(__dirname, rootUrl)))
const port = process.env.PORT
if (process.env.NODE_ENV !== 'production') {
require('dotenv').load()
}
app.use(cors())
// add your API routes here
// e.g:
// app.use('/api', users)
// WARN: must come after all defined routes -> look above (routes definition)
// The "catchall" handler: for any request that doesn't
// match one above, send back React's index.html file.
app.get('*', (req, res) => {
res.sendFile(path.resolve(pathToStaticFiles, 'index.html'))
//res.redirect('/')
})
// start the server and listen
if (!module.parent) {
app.listen(port, () => {
console.log(`Events API server is listening on port ${port}`)
})
}
module.exports = { app, port }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment