How to use the serve-static function in serve-static

To help you get started, we’ve selected a few serve-static examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github raymondsze / create-react-scripts / packages / example-universal-react-app / src / server.js View on Github external
const ASSETS_PATH = path.join(process.cwd(), 'build/assets.json');
const DLL_ASSETS_PATH = path.join(process.cwd(), 'build/dll-assets.json');

console.log('Waiting client-side bundling...');
while (!fs.existsSync(ASSETS_PATH));

const assets = {
  ...JSON.parse(fs.readFileSync(DLL_ASSETS_PATH)),
  ...JSON.parse(fs.readFileSync(ASSETS_PATH)),
};

const app = express();

if (process.env.NODE_ENV === 'production') {
  app.use(serveStatic(path.join(process.cwd(), 'build/client'), { index: false }));
}

app.get('*', async (req, res) => {
  console.log('SeverSideRendering');
  // we don't need to care css or js stuff as already included in data
  // but if we want dynamic html page, we could use the assets variable from the above
  // render the component to root div
  res.set('content-type', 'text/html').send(
    ReactDOMServer.renderToStaticMarkup(
github fooey / gw2w2w-react / routes / statics.js View on Github external
/*
    *
    * Static Routes
    *
    */

    const staticOptions = {
        dotfiles   : 'deny',
        etag       : true,
        maxAge     : '1d',
        // index   : false,
        // redirect: true,
    };

    app.use(serveStatic('public', staticOptions));
    app.use('/nm', serveStatic(process.cwd() + '/node_modules', staticOptions));
    app.use('/node_modules', serveStatic(process.cwd() + '/node_modules', staticOptions));
    app.use('/routes', serveStatic(process.cwd() + '/routes', staticOptions));
    app.use('/views', serveStatic(process.cwd() + '/views', staticOptions));

    express.static.mime.define({
        'text/plain': ['jade', 'map'],
        'text/css'  : ['less'],
        'text/jsx'  : ['jsx'],
    });

};
github nuxt / nuxt.js / packages / server / src / server.js View on Github external
// For serving static/ files to /
    const staticMiddleware = serveStatic(
      path.resolve(this.options.srcDir, this.options.dir.static),
      this.options.render.static
    )
    staticMiddleware.prefix = this.options.render.static.prefix
    this.useMiddleware(staticMiddleware)

    // Serve .nuxt/dist/client files only for production
    // For dev they will be served with devMiddleware
    if (!this.options.dev) {
      const distDir = path.resolve(this.options.buildDir, 'dist', 'client')
      this.useMiddleware({
        path: this.publicPath,
        handler: serveStatic(
          distDir,
          this.options.render.dist
        )
      })
    }

    // Dev middleware
    if (this.options.dev) {
      this.useMiddleware((req, res, next) => {
        if (!this.devMiddleware) {
          return next()
        }
        this.devMiddleware(req, res, next)
      })

      // open in editor for debug mode only
github ustccjw / tech-blog / server / route / index.js View on Github external
const route = app => {
	// public resource
	app.use(favicon(path.join(ROOT, 'public/favicon.ico')))
	app.use(serveStatic(path.join(ROOT, 'public'), { maxAge: '1d' }))
	app.use(serveStatic(path.join(ROOT, 'dist'), { maxAge: '1d' }))

	// route
	app.use('/model.json', falcorMiddleware.dataSourceRoute((req) =>
		new ModelRouter(req.cookies.userId)))

	const templatePath = ENV === 'development' ?
		path.join(ROOT, 'view/dev-index.html') :
		path.join(ROOT, 'view/index.html')

	// default index
	app.get('*', (req, res, next) => {
		match({ routes, location: req.url },
			async (err, redirect, renderProps) => {
				try {
					if (err) {
						throw err
github nuxt / nuxt.js / lib / core / renderer.js View on Github external
// For serving static/ files to /
    const staticMiddleware = serveStatic(
      path.resolve(this.options.srcDir, this.options.dir.static),
      this.options.render.static
    )
    staticMiddleware.prefix = this.options.render.static.prefix
    this.useMiddleware(staticMiddleware)

    // Serve .nuxt/dist/ files only for production
    // For dev they will be served with devMiddleware
    if (!this.options.dev) {
      const distDir = path.resolve(this.options.buildDir, 'dist')
      this.useMiddleware({
        path: this.publicPath,
        handler: serveStatic(distDir, {
          index: false, // Don't serve index.html template
          maxAge: '1y' // 1 year in production
        })
      })
    }

    // Add User provided middleware
    this.options.serverMiddleware.forEach(m => {
      this.useMiddleware(m)
    })

    // Finally use nuxtMiddleware
    this.useMiddleware(nuxtMiddleware.bind(this))

    // Error middleware for errors that occurred in middleware that declared above
    // Middleware should exactly take 4 arguments
github binary-com / webtrader / tests / server.js View on Github external
export const start = () => {
  app = connect()
    .use(serveStatic('dist/uncompressed'))
    .listen(3000);
  console.log('\n\x1b[1;32mConnected web server on http://localhost:3000\x1b[m')
};
export const close = () => {
github fs / backbone-base / gulp / modules / server / production.js View on Github external
export default () => {
  const port = process.env.PORT;
  const middlewares = apiMiddleware() || mockMiddleware();
  const server = connect();

  server.use((req, res, next) => middlewaresStack(middlewares, req, res, next));
  server.use(serveStatic(config.distDir));
  server.listen(port);
  console.log(`Listening on 0.0.0.0:${port}`);
};
github alidcastano / rogue.js / examples / with-styled-components / src / server.js View on Github external
import { BUNDLE_SRC, PUBLIC_DIR } from '@roguejs/cli'
import serveStatic from 'serve-static'
import ReactDOM from 'react-dom/server'
import { ServerStyleSheet } from 'styled-components'
import App from './App'

const app = rogue(App, BUNDLE_SRC, {
  renderToString(node, ctx) {
    const sheet = new ServerStyleSheet()
    const html = ReactDOM.renderToString(sheet.collectStyles(node))
    ctx.app.headTags.push(sheet.getStyleTags())
    return html
  },
})

app.use(serveStatic(PUBLIC_DIR))

export default app
github foxhound87 / rfx-stack / src / web / middleware / serveStatic.js View on Github external
export function serveStaticMiddleware() {
  const app = this;
  const Dir = global.DIR;

  app.use('/build', serveStatic(Dir.staticBuild));
  app.use('/static', serveStatic(Dir.static));
}
github dashukin / react-redux-template / src / server / server.js View on Github external
export const startServer = () => {
  logger.info('Starting express server');
  const server = express();

  logger.info(`Express static dir: ${DIST_CLIENT_STATIC_DIR}`);
  const staticMiddleware = serveStatic(DIST_CLIENT_STATIC_DIR, {
    index: false,
  });

  server.use(helmet());
  server.use(Router());
  server.use(staticMiddleware);
  server.use([
    cookieMiddleware(),
    servicesMiddleware(),
  ]);

  server.use('/api', apiRouter);

  server.get(/.*/, renderMiddleware({
    createApp,
    createAppStore,

serve-static

Serve static files

MIT
Latest version published 2 years ago

Package Health Score

70 / 100
Full package analysis