Story of the backend — Connecting the final dots

Hello and welcome to the final showdown of the backend development journey we had been on for quite sometime now, and I admit the major reason of this journey was so long was the fact that I was a bit delayed in posting the timely blogs.. Well, let’s dwell in the past a healthy amount and bring everything together and finish and possibly host it on a cloud server(personally I prefer AWS because old habits, but it should not be too hard to host on other cloud platforms either).

First things first, if you have landed directly on this blog, I would recommend to go through the previous setup instruction blogs and we can then continue with the final setup and hosting.

Previous blogs can be found here: The Begining , deciding the databases , routes and paths .

The App —

By this point, we have our databases set up and our routes created and ready to serve. We bring together the main app data in the app.ts (or app.js fofr javascript) file. We also create a server to listen to the requests on a separate file where we also do some init tasks. So, lets begin with creating app.ts and server.ts files in the src folder.

Following are the major imports you must make to have a somewhat solid backend

import * as express from ‘express’;import apiRouter from “./routes/index”;import * as cookieParser from ‘cookie-parser’;import errors, {messages} from ‘./config/errors’

apiRouter contains the routing information for our paths we made in one of the previous blogs, and errors.js exports an object that contains message and error names for certain errors that we will send in case out server fails.

Now that we have out imports, We now create an express app and make it attach to middleware to handle requests.

const app = express(); // as simple as that
app.use(express.urlencoded({ extended: false }));
app.use("/", (req, res, next) => {
if (req.hostname === '' || req.hostname === 'localhost') {//redefine hostname as per the hosted link
apiRouter(req, res, next);
}else {

Here the next(); is basically a call to the next middleware to be executed.

You can provide the paths and middlewares to be executed and finally export the app form app.js so that it could be used in the server.js. Also to keep in mind that when the app is put in production environment a lot of checks are added to it.

The Server

Now that we have our app ready lets make it available to serve to requests. We create a server.ts file to store the server logic now.

import app from 'app'; //import the app we created in app.ts
import initialize from 'initialization';
* contains the logic for just doing some setup
* before starting the server like setting up database
* and connecting to it
// Event listener for HTTP server "error" event.function onError(error: NodeJS.ErrnoException) {if (error.syscall !== 'listen') {throw error;}const bind = typeof port === 'string'? 'Pipe ' + port: 'Port ' + port;// handle specific listen errors with friendly messagesswitch (error.code) {case 'EACCES':logger.error(bind + ' requires elevated privileges');process.exit(1);// eslint-disable-next-line no-fallthroughcase 'EADDRINUSE':logger.error(bind + ' is already in use');process.exit(1);// eslint-disable-next-line no-fallthroughdefault:throw error;}}//Event listener for HTTP server "listening" event.function onListening() {const addr = server.address();const bind = typeof addr === 'string'? 'pipe ' + addr: 'port ' + addr.port;logger.verbose('Listening on ' + bind + '...');} // Normalize a port into a number, string, or false.function normalizePort(val: string) {const portNumber = parseInt(val, 10);if (isNaN(portNumber)) {// named pipereturn val;}if (portNumber >= 0) {// port numberreturn portNumber;}return false;}const port = normalizePort(process.env.PORT || '3000');app.set('port', port);//create a serverconst server = createServer(app);// ensure log directorytry {ensureLogsdirectory();} catch (error) {logger.error(error.message);}// Listen on provided port, on all network interfaces.initialize().then(() => {server.listen(port);server.on('error', onError);server.on('listening', onListening);}).catch(error => {logger.error(error.message);});

The above snippet may look scary but in simple sweet terms, what it is doing is, just make one handler function if an error happens or if no error happens, what to do. and eventually we trigger a function that initializes the database and connects to it then make server listen to the given port and set the handlers .. incase there is an error, log the error.

Now, all that is left is check that you have setup npm start command and see the server run.

Congratulation!! you have created a typescript server with connectivity to an SQL database.

Again, this is just a guidance blog and you will still need to do some research, some debugging to actually create a functional backend for your app but this blog intends to give you a starting point.

And with that, We have completed a 4 blog long journey through the overview of creating a backend with technologies that are not really very commonly paired (SQL with express). Hope this was an educational journey and you enjoyed it. To host the backend, on a very overviewy level, just provision a linux VM on AWS, setup nagios and use the documentation to setup the server(really not a complicated process).

In case you have any doubts , please comment below and in-case you want to connect with me, here are the links to my linkedIn, mail: and github.

See you soon with a new technology and a new story(maybe on React / React-native next)



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store