Temporary 'loading' route in Express?

temporary antonym
temporary synonyms
temporarily or temporary
temporary in hindi
temporary meaning in tamil
how to pronounce temporary
temporary quotes
temporary email

I have a web app that takes a moment to load - as it needs to connect to a database, and so some other things that take time.

What's the best way to have a temporary loading route in Express?

I'd like to do something like the following:

const express = require('express')
const app = express()

// Temporary / for if someone hits the server before it's finished starting
app.get('/', (req, res) => res.send(`Loading....`))

// In my non-demo app, there's a router here that takes a moment to load, instead of a timeout. 
setTimeout(function(){
  app.get('/', (req, res) => res.send(`Ready!`))
}, 3 * 1000)

app.listen(3000, () => console.log('Example app listening on port 3000!'))

Routes can't be deleted at runtime, but you can add a middleware that checks if everything is initialized, if it isn't you end the request with: res.send('Loading'); otherwise you go to the next middelware.

let initialized = false;

app.get('/', (req, res, next) => {
    if(!initialized)
       return res.send('Loading...');
    next();
});

app.get('/', (req, res, next) => {
    res.send(`Ready!`);
});

setTimeout(() => initialized = true, 3000);

Temporary Synonyms & Antonyms, a person employed on a temporary basis, typically an office worker who finds employment through an agency. Temporary, transient, transitory agree in referring to that which is not lasting or permanent. Temporary implies an arrangement established with no thought of continuance but with the idea of being changed soon: a temporary structure.

If your app needs some time to load properly, the best option is to NOT let it start the server.

It works very well with i.e. load balancers and multiple containers as they wait for the /health check to pass before they put the container behind the loadbalancer. Which is something you want to do for modern services.

For example this:

import { app } from './app';
import { config } from './config';
import { logger } from './components/ourLog';
import { initPromise } from './components/ourMongo';

const port = config.server.port;

async function startServer() {
    await initPromise;
    app.listen(port, () => {
        logger.info(
            {
                port,
                params: config.params,
                processEnv: process.env,
            },
            'App has started'
        );
    });
}

startServer()
    .catch(err => {
        logger.error({ err }, 'Critical error, cannot start server');
        process.exit(1);
    });

We have component that connects to mongo and it expose initPromise, which is the promise, which is resolved after the connection is sucesfully done and you can start with using the db.

Temporary dictionary definition, and in this use, the word is often shortened to temp. syn: temporary, transient, transitory agree in referring to that which is not lasting or permanent.

You could ping the server "x" seconds to test when it is ready.

Server

We will create a ready variable, that is set to false, when all of your database, api and other things are done doing what they need you set it to true.

We will also create a route that such as /ping that will respond with the value of ready.

const express = require('express')
const app = express()

let ready = false

// Do database stuff, API stuff, etc.
// Set ready to true when ready

// Temporary / for if someone hits the server before it's finished starting
app.get('/', (req, res) => res.send(`Loading....`))

app.get('/ping', (req, res) => res.json({ready}))

app.listen(3000, () => console.log('Example app listening on port 3000!'))
Client

Here we will ping the server every "x" seconds, I set it to 0.5s, once ping returns true, we cancel the timeout and run the initialization code that builds the page.

let timeout

timeout = setInterval(async () => {
  let response = await fetch('/ping')
  let ready = await response.json()
  if (ready.ready) {
    clearInterval(timeout)
    loadpage()
  }
}, 500)

TEMPORARILY, : transitory, transient, fleeting, evanescent, ephemeral, short-lived, temporal, brief, not permanent, not eternal, for a time, of short duration. Renting space in another office building is only a temporary measure. a temporary job or contract lasts only for a short period of time : According to the report, over 6% of the labour force are working on a temporary basis. temporary jobs / contracts / work

TEMPORARY, temporary definition: 1. not lasting or needed for very long: 2. not lasting or needed for very long: 3. not lasting or…. Learn more. 27 synonyms of temporary from the Merriam-Webster Thesaurus, plus 39 related words, definitions, and antonyms. Find another word for temporary.

Temporary, : continuing for a limited amount of time : not permanent. : intended to be used for a limited amount of time. See the full definition for temporary in the English Language Learners Dictionary. temporary. adjective. Hermaphroditism must be regarded as a temporary or transitional form. “Hit the south trail for the temporary cache,” the leader went on. As he leaves them they are reminded of one Temporary, 'once a forward man in religion.' Only a thin film, you see, but enough to form a temporary plug.

Temporary, 1 impermanent, passing. Temporary, transient, transitory agree in referring to that which is not lasting or permanent. Temporary implies an arrangement  Synonyms for temporary in Free Thesaurus. Antonyms for temporary. 51 synonyms for temporary: impermanent, passing, transitory, brief, fleeting, interim, short-lived

Comments
  • On your front end I would just check if (data is not yet available) show Loading... and when it becomes available then show the data. No need for another route and timeouts
  • If you are trying to push Ready! to the client you can't do that without sockets.
  • @VincentNguyen my back end (the route for /) takes a while to load, so if I have any front end at all, the route has loaded.
  • Also you shouldn't be connecting to the database on every request. You should connect when the server starts and have a constantly open connection.
  • @GetOffMyLawn Not trying to push 'Ready' (if I was, I'd use SSE) just to show something for people (probably other devs) who hit / before / is ready.
  • Thanks. It's more than just a DB, there's a few API clients that need to be started, some health checks etc.
  • Well, you can use my approach anyway, just add the middleware that check for everything to be initialized.
  • Thanks @marcos, I've made a couple of minor tweaks to the variable namin but this sounds like the best approach.
  • Already checking for health in production LB. Already waiting to listen on the port until the app has finished starting. I want to be able to show something to a developer who's started his browser and tried to load the app before his local server has finished starting.
  • @mikemaccana - Well thats the problem, you check for /health in LB, it says "yay, I can do work" and then service says "I am not started yet". If you do not call app.listen, you do not expose server and /health does not pass. Which means the LB will wait and try again later to call the /health. And if you start the server after you load everything /health pass as well, it gets behind LB and all developers/users will always hit only working service and dont have to handle any pending status.
  • I'm not talking about production, except in response to your question. I'm talking about showing something useful if a dev hits their local webserver, or there's a catastrophic failure and 0 servers are available. I have a health check in production LB, when it says "yay, I can do work" it can. Hope that makes sense.
  • @mikemaccana - Well you should never put dev local webserver code into the production one. Also if it is deployed on his machine/by him, the log App has started is enough, also he should be able to see if it terminates or not. If it is deployed somewhere, to be really useful, it should imitate the production as close as possible.
  • "Well you should never put dev local webserver code into the production one" how do you expect to develop software if you don't use the same code in production and on your dev webserver? I have an "App is ready". Not everyone reads every console message.
  • Client is a browser. Having a machine so the setInterval rather than a person isn't an answer to the question I am asking.