Express-js Boilerplate with User Authentication

I couldn’t find a complete user authentication system for Expressjs, so I wrote this one.

For the impatient, the code resides at Github .

Mysql

It uses MySql for user data, and as a session store, too. I tried to make the code flexible. It’s easy to change MySql for something else.
There is no need to use the same database system for the session store. I did it for simplicity only.

Configuration

It uses .env file for the basic configuration of the application. That is, just editing the .env is enough to have the application up and running.

In addition there are a few configurable parameters in /config directory.

“Remember me” cookie duration.

Session store, session duration.

Email send configuration.

Authentication

The authentication system includes:

1. User registration, login based on passport.

2. Forgot – reset password functionality.

     By default reset password code is valid for 1 hour. Configurable.

3. “Remember me” cookie.

      By default valid for 360 days. Configurable.

4. Two user levels, regular and administrator. Not configurable.

Easy to extend in more levels with some coding.

5. Throttling protection for DOS attacks. Configurable.

      By default it allows two requests per two seconds.

6. Xsrf protection.

Interface

The interface is taken from Brad Traversy’s presentation . I only changed the parts I had to.

I believe it is easy to switch the interface with another one, according to the project requirements.

Registration

When a user is registered in the application he becomes an administrator, if there is no other user in the database.

There is no activation email. Users are active immediately after registration. I didn’t include an activation step, because not all projects need it. It is quite easy to add it, if there is such a requirement. 

Anyway, there is always the administrator to control which users are allowed, and which not.

Dashboard

https://cdn.filestackcontent.com/zpiduDdQSiWT8MCXQGii

There is a basic admin dashboard, where the admin can make, or cancel, other admins.

The admins can activate, deactivate other users. There is no user deletion, only deactivation.

Remember me

The remember me cookie does not contain the user ID but the UUID, which carries no useful info for an attacker. This is the only reason to include a UUID in the “users” database table.

The content of the cookie is the UUID and the “remember me” token. The “remember me” token hash is kept in the database. The token is verified
as a password.

The “remember me” cookie value, and the “forgot password” key, are treated as passwords, because they are in fact equivalent to passwords.

Dependencies

I tried to keep the number of dependencies low as possible, to not restrict the developer in the package selection for the main project.

No tags for this post.

Related posts

How To Connect SailsJS with GraphQL Guide

If you’re having troubles with organizing API for the Node.js app, using the Sails.js framework with the GraphQL, know that you’re not the only one – we’ve been there too.

Since this is not an every-day combination of technologies, it was challenging to define the anatomy of such app and its tests, but we did it!

Are you asking yourself questions like these:

  • How will I organize all the queries and mutations?
  • Where will the schema be defined?
  • What should I do with the authorization and other utilities?

If the answer is yes, this article has answers to all of your questions!

Let’s Start!

First, we’ll generate our sails app (I assume you have installed NodeJS and Sails, if not here’s a little help how to get started):
 $ sails new graphql-app

If generated successfully, you should get a small app with a structure like this:

First, we will go through api/ folder, what it and its subfolders contain:

Controllers

As the name says, this folder will contain our controllers, or, may I say, a controller since we are using GraphQL.

This sentence really needs a text-decoration:underline GraphQL needs only one controller to handle all the requests sent to the API.

The purpose of the controller is to redirect requests to the right query or the mutation field and return the resolved value back to the client.

Graphql

This folder won’t be created by default, so we’ll need to create it ourselves.

Here, we will store all of our GraphQL related files: queries, mutations, types, schema, etc. We created a folder for each entity in our app’s model and stored the queries and mutations for it, and also defined type and utils regarding the entity in that folder.

So, the user model will have it’s own folder with UserQueries.js, UserMutations.js, UserType and UserUtils.js (if necessary), profile model we’ll have its own related files and so on…

Here’s a visual representation:

The root folder will contain the schema.js file, in which we’ll combine all the queries and mutations into one big GraphQL schema.

We initially chose SailsJS due to how similar it was to Rails.

Model

Once again, this is a self-explanatory directory which will contain all of our app models.

A model represents a collection of structured data, usually corresponding to a single table or collection in a database. We will hold basic models in the root of the model/ folder, and all the models related to our basic models in a separate folder.

For example, basic information about a user will be held in User.js model, but his details will be stored in Profile.js model, which will be contained in subfolder models/user/ :

Policies

Policies in SailsJS are versatile tools for authorization and access control. The policy file is defined for a specific route and since we will have only one controller accessed through POST /graphql, we will have only one policy file.

Through the policy, we will allow or deny clients’ access to our GraphQL controller (our client is an universal ReactJS app!).

Responses

Sails comes with a handful of the most common response types by default and they can be found in api/responses directory. You are free to edit them, add new ones or remove them if you think they are unnecessary.

Since all the traffic is going through one specific controller, we will keep only 2 of those responses and create a new one. We will keep ok.js and badRequest.js, since those are the only 2 responses our GraphQL controller can provide us, and we will create unauthorized.js which we will send if the request hasn’t passed our policy mentioned above.

Services

Services are stateless libraries of functions (helpers) you can use from anywhere in your Sails app. For example, you might have an EmailService.js which tidily wraps up one or more helper functions so you can use them in more than one place within your application.

Services and their helpers are the best and simplest way to build reusable code in a Sails app. The greatest thing about them is that they are globalized, which means you can use them without having to require() or import them.

We use api/services/ for reusable tools like S3Upload.js, Honeybadger.js, PusherService.js etc.

Let’s now take a look how the tests should look like.

Test

Sails does not automatically create test/ folder for us, so we’ll go ahead and create one ourselves. The test folder should mimic the structure of our api folder which will lead to better DX, easier debugging of the code and resolving issues (everything a good programmer wants).

To create some quality tests, we will need an assets/ folder for holding the files we need in tests, we will need factories/ for a clean way to create our test data objects, graphql/ where we will put the tests dedicated to testing queries and mutations and models/ for unit testing.

As said before, the anatomy of test/ folder is identical to api/ folder structure, except we have additional folders for factories and assets.

This covers all the details regarding how we organize our code. We hope that this article will inspire you to write some great, well-structured Sails apps!

Previously published at https://kolosek.com/sails-graphql-guide/

No tags for this post.

Related posts

16 JavaScript Protips [2020 Edition]

When I began learning JavaScript, I made a list of every time-saving trick that I found in other people’s code, on code challenge websites, and anywhere other than the tutorials I was using.

Each of these tricks accomplishes tasks that most developers need to do on a daily basis. Depending on your experience you might already know
some of these tricks, while others will blow your mind.

In this article, we’ll go over a list of tricks that will make you a better developer and supercharge your JavaScript skills.

1. Filter Unique Values

The Set object type was introduced in ES6, and along with …, the ‘spread’ operator, we can use it to create a new array with only the unique values.

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)]; console.log(uniqueArray); // Result: [1, 2, 3, 5]

Before ES6, isolating unique values would involve a lot more code than that!

This trick works for arrays containing primitive types: undefined, null, boolean, string and number . (If you had an array containing objects, functions or additional arrays, you’d need a different approach!)

2. Every and some

The every and some functions are functions that not all developers are familiar with. However, they can be very useful in certain situations. Let’s start with the every function. You can use this function if you want to know whether all elements of an array pass a certain test. Essentially what this is doing is going through each element of the array and checking to see if they’re all true.

This might sound a little abstract to you, so let’s lets take a look at the following example. It’s not as complex as it sounds.

const random_numbers = [ 13, 2, 37, 18, 5 ]
const more_random_numbers = [ 0, -1, 30, 22 ] const isPositive = (number) => { return number > 0
} random_numbers.every(isPositive); // returns true
more_random_numbers.every(isPositive); // returns false

The every function returns a boolean. If all elements in the array pass the test, true will be returned. If one of the elements in the array fails the test, false will be returned.

You could also use an anonymous function as a tester function if you’d like to:

random_numbers.every((number) => { return number > 0
})

The some function almost works exactly the same as the every function. There’s only one major difference: the some function tests whether at least one element in the array passes the test implemented.

If we take a look at the previous example and use the some function instead of the every function both arrays will return true, since both arrays contain a positive number.

const random_numbers = [ 13, 2, 37, 18, 5 ]
const more_random_numbers = [ 0, -1, 30, 22 ] const isPositive = (number) => { return number > 0
} random_numbers.some(isPositive); // returns true
more_random_numbers.some(isPositive); // returns true

3. Short-Circuit Evaluation

The ternary operator is a quick way to write simple (and sometimes not-so-simple) conditional statements, like these:

x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';
But sometimes even the ternary operator is more complicated than necessary. Instead, we can use the ‘and’

&&

and ‘or’ || logical operators to evaluate certain expressions in an even more concise way. This is often called ‘short-circuiting’ or ‘short-circuit evaluation’.

How It Works

Let’s say we want to return just one of two or more options.

Using

&&

will return the first

false
 

or ‘falsy’ value. If every operand evaluates to true , the last evaluated expression will be returned.

let one = 1, two = 2, three = 3;
console.log(one && two && three); // Result: 3 console.log(0 && null); // Result: 0
Using || will return the first

true
 

or ‘truthy’ value. If every operand evaluates to

false
 

, the last evaluated expression will be returned.

let one = 1, two = 2, three = 3;
console.log(one || two || three); // Result: 1 console.log(0 || null); // Result: null

Example 1

Let’s say we want to return the

length

of a variable, but we don’t know the variable type.

We could use an

if/else

statement to check that

foo

is an acceptable type, but this could get pretty longwinded. Short circuit evaluation allows us to do this instead:

return (foo || []).length;
If the variable

foo

is truthy, it will be returned. Otherwise, the

length
 

of the empty array will be returned: 0 .

Example 2

Have you ever had problems accessing a nested object property? You
might not know if the object or one of the sub-properties exists, and
this can cause frustrating errors.

Let’s say we wanted to access a property called

data

within

this.state

, but

data

is undefined until our program has successfully returned a fetch request.

Depending on where we use it, calling

this.state.data

could prevent our app from running. To get around this, we could wrap it in a conditional:

if (this.state.data) { return this.state.data;
} else { return 'Fetching Data';
}

But that seems pretty repetitive. The ‘or’ operator provides a more concise solution:

return (this.state.data || 'Fetching Data');
We can’t refactor the code above to use

&&

. The statement

'Fetching Data'
&& this.state.data

will return

this.state.data

whether it is

undefined

or not. This is because

'Fetching Data'

is ‘truthy’, and so the

&&

will always pass over it when it is listed first.

A New Proposed Feature: Optional Chaining

There is currently a proposal to allow ‘optional chaining’ when
attempting to return a property deep in a tree-like structure. Under the
proposal, the question mark symbol

?

could be used to extract a property only if it is not

null

.

For example, we could refactor our example above to

this.state.data?.()

, thus only returning

data

if it is not

null 

.

Or, if we were mainly concerned about whether

state

was defined or not, we could return

this.state?.data

.

4. Convert to Boolean

Besides the regular boolean values

true

and

false

, JavaScript also treats all other values as either ‘truthy’ or ‘falsy’.

Unless otherwise defined, all values in JavaScript are ‘truthy’ with the exception of

0

,

""

,

null

,

undefined

,

NaN

and of course

false

, which are ‘falsy’.

We can easily switch between true and false by using the negative operator ! , which will also convert the type to

"boolean"

.

const isTrue = !0;
const isFalse = !1;
const alsoFalse = !!0; console.log(isTrue); // Result: true
console.log(typeof true); // Result: "boolean"
This kind of type conversion can be handy in conditional statements, although the only reason you’d choose to define

false

as

!1

is if you were playing code golf!

5. Conditionally setting a variable

Conditionally setting a variable is both easy and makes your code look more elegant. There’s no need to write an if-statement when applying this trick — which personally is one of my favorite tricks in JavaScript.

So how can you conditionally set a variable?

const timezone = user.preferred_timezone || 'America/New_York'
In the example above we check if the user has a preferred timezone. If the user has a preferred timezone, we use that timezone. If the user doesn’t have a preferred timezone we use the default timezone, which is

‘America/New_York’

.

This code looks so much cleaner than when using an if-statement.

let timezone = 'America/New_York' if (user.preferred_timezone) { timezone = user.preferred_timezone
}

Looks much cleaner, doesn’t it?

6. Convert to String

To quickly convert a number to a string, we can use the concatenation operator + followed by an empty set of quotation marks

""

.

const val = 1 + ""; console.log(val); // Result: "1"
console.log(typeof val); // Result: "string"

7. Convert to Number

The opposite can be quickly achieved using the addition operator

+ 

.

let int = "15";
int = +int; console.log(int); // Result: 15
console.log(typeof int); Result: "number"

This may also be used to convert booleans to numbers, as below:

console.log(+true); // Return: 1
console.log(+false); // Return: 0
There may be contexts where the

+

will be interpreted as the concatenation operator rather than the addition operator. When that happens (and you want to return an integer, not a float) you can instead use two tildes:

~~

.

A tilde, known as the ‘bitwise NOT operator’, is an operator equivalent to

 -n — 1 

. So, for example,

~15

is equal to

-16

.

Using two tildes in a row effectively negates the operation, because

 — ( — n — 1) — 1 = n + 1 — 1 = n 

. In other words,

~ — 16

equals

15

.

const int = ~~"15" console.log(int); // Result: 15
console.log(typeof int); Result: "number"
Though I can’t think of many use-cases, the bitwise NOT operator can also be used on booleans:

~true = -2

and

~false = -1

.

8. Casting values in Arrays

Sometimes you want to cast all values in an array. One of those
occurrences could be when you’re using the triple equals operator to
check whether a certain number exists in an array, for example.

I lately ran into a problem where I had a multi-select. The HTML
values of the select options were strings instead of integers, which
makes sense. The array of selected values looked like this:

let selected_values = [ '1', '5', '8' ]

The problem was that I was checking if a certain integer existed in the
array of the selected values. Without success. I used an intersect
function that used the triple equals operator. And since ‘5’ !== 5 I had to find a solution.

The prettiest solution, in my opinion, was to cast all values in the
array to an integer. When trying to do this I stumbled upon a painfully
simple, yet elegant, solution.

selected_values = selected_values.map(Number) // [ 1, 5, 8 ]

Instead of casting all values to an integer, you could also cast all values in
the array to a boolean by simply changing the argument of the map
function.

selected_values = selected_values.map(Boolean)

9. Quick Powers

Since ES7, it has been possible to use the exponentiation operator

**

as a shorthand for powers, which is faster than writing

Math.pow(2, 3)

. This is straightforward stuff, but it makes the list because not many tutorials have been updated to include this operator!

console.log(2 ** 3); // Result: 8

This shouldn’t be confused with the ^ symbol, commonly used to represent exponents, but which in JavaScript is the bitwise XOR operator.

Before ES7, shorthand existed only for powers with base 2, using the bitwise left shift operator

<< 

:

// The following expressions are equivalent: Math.pow(2, n);
2 << (n - 1);
2**n;
For example,

2 << 3 = 16

is equivalent to

2 ** 4 = 16

.

10. Quick Float to Integer

If you want to convert a float to an integer, you can use

Math.floor() 

,

Math.ceil()

or

Math.round()

. But there is also a faster way to truncate a float to an integer using

|

, the bitwise OR operator.

console.log(23.9 | 0); // Result: 23
console.log(-23.9 | 0); // Result: -23
The behaviour of

|

varies depending on whether you’re dealing with positive or negative numbers, so it’s best only to use this shortcut if you’re sure.

If

n

is positive,

n | 0

effectively rounds down. If

n

is negative, it effectively rounds up. To put it more accurately, this operation removes whatever comes after the decimal point, truncating a float to an integer.

You can get the same rounding effect by using

~~

, as above, and in fact any bitwise operator would force a float to an integer. The reasons these
particular operations work is that — once forced to an integer — the
value is left unchanged.

Remove Final Digits

The bitwise OR operator can also be used to remove any amount of
digits from the end of an integer. This means we don’t have to use code
like this to convert between types:

let str = "1553"; Number(str.substring(0, str.length - 1));

Instead, the bitwise OR operator allows us to write:

console.log(1553 / 10 | 0) // Result: 155
console.log(1553 / 100 | 0) // Result: 15
console.log(1553 / 1000 | 0) // Result: 1

11. Object destructuring

Once you know about object destructuring it’s probably something that you’re going to be using every single day.

But what exactly is destructuring?

Destructuring is a JavaScript expression that allows you to extract
data from arrays, objects, maps and sets into their own variable. It
allows you to extract properties from an object or items from an array,
multiple at a time.

Let’s take a look at the following example where we have a user
object. If you want to store the user’s name in a variable you have to
assign it to a variable on a new line. And if you want to store the
gender as well in a variable, you’d have to do the same again.

const user = { name: 'Frank', age: 23, gender: 'M', member: false
} const name = user.name
const gender = user.gender

With destructuring you can directly get the variables for the object’s properties using the following syntax:

const { name, age, gender, member } = user; console.log(name) // Frank
console.log(age) // 23
console.log(gender) // M
console.log(member) // false

12. Automatic Binding in Classes

We can use ES6 arrow notation in class methods, and by doing so
binding is implied. This will often save several lines of code in our
class constructor, and we can happily say goodbye to repetitive
expressions such as

this.myMethod = this.myMethod.bind(_this_)

!

import React, { Component } from React;export default class App extends Compononent { constructor(props) { super(props); this.state = {}; }myMethod = () => { // This method is bound implicitly! }render() { return ( <> <div> {this.myMethod()} </div> </> ) }
};

13. Better debugging using performance

One of the things that you’ll do a lot as a developer is debugging.
However, debugging is more than just printing out a bunch of log
messages in your console using console.log.

Did you know that the console object has a great way to analyze
performance of pieces of your code? However, most developers only know
about the standard console.log way of debugging their code.

The console object has way more helpful functions. It has a time and timeEnd function that can help you analyzing performance. It works really simple.

In front of the code that you want to test, you call the console.time
function. This function has one argument, which takes a string that
describes what you want to analyze. At the end of the code that you want
to test, you call the console.timeEnd function. You give this
function the same string as the first parameter. You’ll then see the
time it took to run the code in your console.

console.time('loop') for (let i = 0; i < 10000; i++) { // Do stuff here 
} console.timeEnd('loop')

14. Truncate an Array

Arrays

If you want to remove values from the end of an array destructively, there’s are faster alternatives than using

splice()

.

For example, if you know the size of your original array, you can re-define its length property, like so:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4; console.log(array); // Result: [0, 1, 2, 3]
This is a particularly concise solution. However, I have found the run-time of the

slice()

method to be even faster. If speed is your main goal, consider using something like this:

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4); console.log(array); // Result: [0, 1, 2, 3]

15. Get the Last Item(s) in an Array

Arrays

The array method

slice()

can take negative integers, and if provided it will take values from the end of the array rather than the beginning.

let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]

16. Format JSON Code

JSON

Lastly, you may have used JSON.stringify before, but did you realise it can also help indent your JSON for you?

The stringify() method takes two optional parameters: a replacer function, which you can use to filter the JSON that is displayed, and a space value.

The space value takes an integer for the number of spaces you want or a string (such as ‘\t’ to insert tabs), and it can make it a lot easier to read fetched JSON data.

console.log(JSON.stringify({ alpha: 'A', beta: 'B' }, null, '\t')); // Result:
// '{
// "alpha": A,
// "beta": B
// }'

Overall, I hope you found these tips as useful as I did when I first discovered them.

Got any JavaScript tricks of your own? I’d love to read them in the comments below!

No tags for this post.

Related posts

Creating Todo Web App Using Vanilla JavaScript

today we will create a basic todo app to understand the basics of javascript. In this web app, one can create notes and delete like Google Keep or Evernote.

basic setup :

create three files for html,css and javascript. To create these files run command

$ touch index.html index.css index.js

step 1 : now edit index.html file

<!DOCTYPE html>
<html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>todo</title> <link rel="stylesheet" href="index.css">
</head> <body> <h1>&nbsp;&nbsp;&nbsp; TODO APP &nbsp;&nbsp;&nbsp;</h1> <div class="container"> <div class="box"> <input type="text" name="add" placeholder="todo-item" id="box" /> <input type="button" value="add" onclick="add_item()" /> <ul id="list_item"> </ul> </div> </div> <script type="text/javascript" src="index.js"></script>
</body> </html>

step 2 :now time to add some css , edited index.css file.

* { padding: 0; margin: 0; box-sizing: border-box; font-family: cursive;
} body { background: #f2f2f2; overflow: auto;
} h1{ text-align: center; margin: 5%; font-size: 3rem; text-decoration: underline;
} .container{ display: flex; align-items: center; justify-content: center;
} .box { background: lightgrey; border: 1px solid black; padding: 3%; width: 50%; height: auto; overflow: auto; display: inline-block; box-shadow: 0px 5px 25px black; margin-bottom: 3%; border-radius: 5%;
} input { text-align: center; padding: 4%; border: 0;
}
input[type="text"]{ margin-left: 5%; width: 70%; } input[type="button"] { padding: 4% 6% 4% 6%; text-transform: uppercase; font-weight: bolder;
} input[type="button"]:hover { background: lightblue; transition: 1s ease-out;
} ul { text-align: lleft; padding-left: 10%; padding: 7%; font-size: 2rem; list-style: circle;
} li:hover{ color:red; margin: 4%; transition: 1.5s ease; cursor: pointer;
}

step 3 :edit index.js file to add some functionality

//function called while clicking add button
function add_item() { //getting box and ul by selecting id; let item = document.getElementById("box"); let list_item = document.getElementById("list_item"); if(item.value != ""){ //creating element and adding value to it let make_li = document.createElement("LI"); make_li.appendChild(document.createTextNode(item.value)); //adding li to ul list_item.appendChild(make_li); //reset the value of box item.value="" //delete a li item on click  make_li.onclick = function(){ this.parentNode.removeChild(this); } } else{ //alert msg when value of box is "" empty. alert("plz add a value to item"); } }
No tags for this post.

Related posts

How to Use Eslint With Webpack And ES6 Modules

Today we are going to talk about eslint and webpack. This is not going to teach you how to install eslint in your project, I will assume that you already did.

First of all, when you are new to eslint and want to auto-fix your JavaScript files, so you run

npx eslint --fix .

but, you have this main.js that webpack kindly generated for you to make your code separated by modules, work.

So, you get this result:

Even though the code still working, you are not going to pass eslint rules. We don’t need to check this file with eslint, so what do we do?

We need to create a file in the root directory called .eslintignore

As you can see, the only line of code that you need to write is dist/main.js

And that’s it, next time you use

npx eslint .

or

npx eslint --fix .

eslint will ignore this file.

Happy Coding!

No tags for this post.

Related posts

Express.js Integration Guide for Passwordless Authentication with DID.app

Just want the code? Find this example on github

What is DID.app

Me and my cofounder have been building DID so that we can all stop using passwords. Most of us have too many passwords and we don’t like using them

DID.app is an Identity Provider, that authenticates users by verifying access to either an email address or securely stored private key.

This allows your users to sign in with just a single click.

Requirements

This tutorial will require you to have Node.js and Express installed.

New Express project

npx express-generator --view=pug myapp
cd myapp
npm install
Install

openid-client

and

cookie-session

from npm.

npm install --save openid-client cookie-session

Add sessions to the application

We will use cookie-session so that we can keep a user signed in after we have authenticated them.
To use it, require the module and add to the apps middleware in

app.js

.

// other dependencies
var cookieSession = require("cookie-session"); // other middleware
var { SESSION_SECRET } = process.env;
app.use(cookieSession({ name: "myapp", secret: SESSION_SECRET }));

It is best practise to keep your session secret out of your source code.

Fetch OpenID Connect configuration

Only routes for handing authentication will require the OpenID Configuration for DID.app.

Create a routes file for sessions

routes/session.js

and configure the client library.

var express = require("express");
var router = express.Router();
var { Issuer } = require("openid-client"); var { CLIENT_ID, CLIENT_SECRET } = process.env; var clientPromise = Issuer.discover("https://did.app").then(function(issuer) { console.log("Discovered issuer %s %O", issuer.issuer, issuer.metadata); return new issuer.Client({ client_id: CLIENT_ID, client_secret: CLIENT_SECRET });
}); // ...
The

client_id

in

client_secret

are fetched from the environment,

we will generate them later.

Create File for sign in routes

Signing in, or up, using the OpenID connect flow requires two endpoints.

One endpoint redirects the user to the OpenID provider (in this case DID.app) to authenticate themselves. A second callback endpoint is where the result of authenticating is handled.

Add both of these into the session routes file.

// ... router.get("/authenticate", function(req, res, next) { clientPromise.then(function(client) { var authorizationUrl = client.authorizationUrl({ scope: "openid", redirect_uri: "http://localhost:3000/session/callback" }); res.redirect(authorizationUrl); });
}); router.get("/callback", function(req, res, next) { clientPromise .then(function(client) { var params = client.callbackParams(req); return client.callback("http://localhost:3000/session/callback", params); }) .then(function(tokenSet) { var claims = tokenSet.claims(); console.log(claims); req.session = { userId: claims.sub }; res.redirect("/"); });
}); module.exports = router;
Add the session routes to the express app in

app.js

.

// other dependencies
var sessionRouter = require("./routes/session"); // ... app.use("/", indexRouter);
app.use("/users", usersRouter);
// new routes
app.use("/session", sessionRouter);

Display authentication status

Our users need a button that lets them sign in.

To add one to the homepage the route handler checks if there is already a user session, if so we make this user id available to the view.

Make these changes to

routes/index.js

.

router.get("/", function(req, res, next) { var session = req.session || {}; res.render("index", { title: "Express", userId: session.userId });
});

In the view we use the user id to show them some information about them, or if no user a sign in button this code to show a button

Add this snippet into

views/index.pug

.

if userId span User ID #{userId}
else a.button.action(href='/session/authenticate') Sign in

Setup the App on DID

You will need a DID account. Sign up to create one now. After signing up, you will be directed to set up your first app.

Because we will run on localhost we need to use test app, select test mode.

After setting the details for the app, copy the client id and secret for use in our application.

Try it out

Start Express, passing in the required configuration as environment variables.

CLIENT_ID=test_abc \
CLIENT_SECRET=test_abcdef \
SESSION_SECRET=somesecret \
npm start
Visit localhost:3000, you should see your new Express app with a shiny sign in button.
Any problems, see this commit for the complete set of changes.

Have a question?

If you have any further questions contact us at [email protected] .

Previously published at https://dev.to/crowdhailer/express-js-integration-guide-for-passwordless-authentication-with-did-app-246p

No tags for this post.

Related posts

Why You Should Learn Vanilla JS Before Frameworks

First of all, I want to start by explaining that vanilla JS is not a framework, now in 2020 is well known that vanilla JS is “plain javascript” this means pure JS without frameworks.

what about JQuery?

JQuery was a popular framework that got popularity from its launch date in
2006 and it served well for around 10 years, so if you ask something to
google about JS you are going to find answeres written in JQuery. but
again we are on 2020 and this changed a lot since that, the release of
ES6 and new frameworks like(React, Angular, Vue) written the death
sentence of JQuery, to top of, in the last version of another important
framework Bootstrap who is going to remove JQuery from their core
(finally) in the version 5.

But coming back to the main object of this article you’ll found a lot of JQuery code and you’d be tempted to use it instead of JS. don’t do it. search for vanilla JS solutions and learn it. is harder but pays
well at the end.

What about JS Frameworks?

there are 3 main JS frameworks right now, React, Vue and Angular, and there are more, but I’m not going to talk about them now, the truth is that
all frameworks share similitude although they’re different each other,
but at the end they all use JS and before to dig into them its important to have a solid JS foundation, this way you can focus on the concepts
and patterns, that is what actually frameworks are.

more reasons?

I’m not the only one that says this. if you go through The Odin’s project path you will see that they focus on JS before frameworks, or Freecodecamp who has a big learning platform and yes they have a big JS section before frameworks.

One of the reasons they do that is because you use a lot of iteration methods in frameworks so it is not all about syntax.

Last but not least once you know JS moves from one framework to another is going to be a piece of cake.

I hope this article helped you a little bit to get the motivation to
learn vanilla JS. remember always keep learning and get fun!.

No tags for this post.

Related posts

How to Handle REST API Requests in React

REST APIs are commonly used in web development. They are programming interfaces that web apps use to ‘talk’ to each other. They are used to access features and data. ‘REST’ (Representational State Transfer) is a concept that defines the APIs properties. This article will focus on the use of web-based APIs to retrieve data from a database.

Axios is an npm package that allows apps to send HTTP requests to web APIs. To use Axios within your React app, use the following commands:

npm install axios

or

yarn add axios

Before creating the react component, import React and Axios into the file as follows:

import React from 'react';
import axios from 'axios';

Axios requests were utilised within the React lifecycle method ‘componentWillMount’. Although this method has since been deprecated, it is still available for use at the time of this writing. It will continue to be until the release of React 17. It isn’t considered safe for use when asynchronous rendering is required. In its place, you should use the method ‘componentDidMount’.

This method runs after the component has been updated to the DOM, and is a good place to register API calls. The basic structure this far is as follows:

class YourComponent extends React.Component { constructor(props) { super(props); this.state = { posts: [] } } componentDidMount() { // Your axios request here } render() { return ( // Your jsx goes here ); }
}

Axios requests have the following basic structure:

axios({ method: 'http request method', url: 'Api url' });

As seen above, basic requests take an object as an argument. In that object, method and URL keys are specified. The HTTP request method type and the API URL are set as their respective values.

GET Requests

With this basic pattern in mind, an Axios GET request would be as follows:

const apiUrl = 'https://your-api.com/'; axios({ method: 'get', url: `${apiUrl}` });

When API receives the request and processes the request, a response is sent. The component will need to handle the data received in some way before it can be used in the app. In this example, we defined a key in our state, named ‘posts’ and set it equal to an empty array. Axios requests are asynchronous. We need to handle the response by chaining ‘then’ on to the end of the request.

Inside the then block, we can update the component’s state as follows:

axios({ method: 'get', url: `${apiUrl}` }) .then(response => { this.setState({ posts: response.data }) });

(PS. if we were utilising redux for state management, we could call a dispatch function in the ‘then’ block. That way, we can save the response data in the redux store).

POST Requests

In the case of a typical POST request, data is passed along with the API request. This data usually can reside either in the component’s state or a redux store. Usually, the data that the user wishes to post to the database is obtained from a form. We would update the component’s state with the handleChange function. Our Axios request would be made in the handleSubmit function.

When the form is submitted, a POST request is sent to the API. This can be done as follows:

class YourComponent extends React.Component { constructor(props) { super(props); this.state = { post: '' } } handleChange(e) { const { value } = e.target; this.setState({ post: value }); } handleSubmit(e) { e.preventDefault(); const { post } = this.state; axios({ method: 'post', url: `${apiUrl}/posts`, data: post }) } render() { return ( // Your form resides here ); }
}

DELETE Requests

DELETE requests are similar to POST requests. They are made upon interaction with a button in the view. In this case, a handleClick function can be employed to make the request when a ‘delete’ button is clicked. This can be done as follows:

class YourComponent extends React.Component { constructor(props) { super(props); this.state = { posts: [ { id: 1, content: 'The first post' } ] } this.handleClick = this.handleClick.bind(this); } handleClick(e) { e.preventDefault(); const { id } = e.target; const apiUrl = 'https://your-api.com/'; axios({ method: 'delete', url: `${apiUrl}/posts/${id}` }) } render() { const { posts } = this.state; return ( <div> {posts.map(post => ( <div key={post.id}> <p>{post.content}</p> <div> <input type="button" id={post.id} value="Delete" onClick={this.handleClick} /> </div> </div> ))} </div> ); }
}

Once the button is clicked, the DELETE request is sent to the api and the post is removed from the database. For this to be reflected on the front-end, another GET request has to be sent to update the component’s state.

Requests with JWT

JWT (JSON Web Tokens) can be used to authenticate users in web-based applications. These tokens are usually generated by sending a POST request to a properly configured API. Once the token is generated, they are stored for use via localStorage. In such a case, the token would need to form part of the HTTP request made.

To illustrate this, we’ll revisit the GET request example:

const apiUrl = 'https://your-api.com/';
const token = `Bearer ${localStorage.getItem('jwt')}`; axios({ method: 'get', url: `${apiUrl}`, headers: { Authorization: token }
});

The token is passed as another key in the object argument passed to the Axios call. POST and DELETE requests can be altered in a similar fashion with the token being passed in via a ‘headers’ key.

And there you have it. This was a very concise look at Axios requests in react front-end components.

No tags for this post.

Related posts

How to Build an Omni-Channel Micro-App with Node.js and Express in 2 Hours

I’m the CTO of ONEm Communications Ltd. We’ve built a developer framework and platform that allows developers to rapidly build fully functional omni -channel micro-apps.

In this article, I’ll show you how to build an example micro-app from scratch using our simple Node.js SDK. The tutorial assumes a basic knowledge of Node.js.

We’ll retrieve the movie details courtesy of the free api provided by http://themoviedb.org (please make sure to abide by their terms).

We’ll write a web widget that can be integrated into any website…

And the same codebase will also support an SMS client out of the box…

The ONEm platform lets you host your micro-app anywhere on the Internet. For local testing, We’ll use ngrok to provide a publicly accessible URL so that we have a bridge between our app running on localhost and the ONEm Framework.

Pre-requisites

Micro-app basics

When users make requests from web a widget or via SMS, the ONEm Framework will invoke an HTTP callback to the micro-app’s web server. The micro-app should respond with HTTP status code 200 and include, in the response body, some JSON which tells the ONEm Framework how to render the response to the user. If you’re intrigued and want to know more, you can checkout the developer docs at https://developer-docs.onem.zone.
Our Node.js SDK provides an abstraction of the JSON format so you don’t have to worry about the details. You have two options, you can use the SDK to produce JSON by passing parameters to the functions provided, or alternatively you can use a templating library and write your micro-app’s views in HTML 🙂 In this tutorial, we’ll be using the second option and specifically pug as the templating language, you can use ejs instead if you prefer.

Ok, enough chat, let’s get coding!

Project Structure and Code

The code used in this tutorial can be accessed via the git repository here

Our project structure will look like this:

/
index.js
package.json
.env
/app_api
/routes
index.js
/views
landing.pug
movieView.pug
/public
/index.html
Install Express and the project’s base dependencies:
 $ npm install express dotenv jwt-simple request-promise url-join

We’ll also use the ONEm Framework’s Node.js SDK:

$ npm install onemsdk

Create an index.js in the project root with the following content:

require('dotenv').config()
const express = require('express')
const api = require('./app_api/routes') const app = express()
const PORT = process.env.PORT || 3000 app.use(express.json())
app.use(express.static(__dirname + '/public'));
app.use('/api', api) app.get('/', function (req, res) { res.sendFile('/public/index.html', { root: __dirname })
}) app.get('*', function (req, res) { res.sendFile('/public/index.html', { root: __dirname })
}) app.get('/*', function (req, res) { res.sendFile('/public/index.html', { root: __dirname })
}) app.listen(PORT, () =&gt; console.log(`Example micro-app listening on port ${PORT}`))

When users make requests from our micro-app, such as selecting a menu option or submitting a form, the ONEm Framework will issue a HTTP request to the micro-app’s callback path. In the index.js we set /api as the ‘basepath’ for all requests coming from the ONEm Framework with this line:

app.use('/api', api)

When the micro-app is launched for the first time by a user, the ONEm Framework will display the micro-app’s “landing page”. This is a bit like the index.html of a typical web application. The landing page is invoked by the ONEm Framework issuing a request to the micro-app’s API base path, in our case /api.

So we’ll want our app to handle a basic call to GET /api and respond with some initial content that the user will see.

For our example, we’ll create a static menu, so that our users can view three different movies:

When the user clicks on a movie title, we’ll show the movie’s image and description.

First off, let’s create the landing menu options by creating a landing.pug in the /views folder:

section header Movie Menu ul li a(href='/movie/76341/') Mad max li a(href='/movie/419704/') Ad Astra li a(href='/movie/454626/') Sonic the Hedgehog

And let’s connect the base route in Express in /routes/index.js:

const jwt = require('jwt-simple')
const express = require('express')
const request = require('request-promise')
const urlJoin = require('url-join')
const { loadTemplate } = require('onemsdk').parser
const { Response } = require('onemsdk') const api = express.Router() // get this by signing up for an account at https://www.themoviedb.org/
const READ_ACCESS_TOKEN = process.env.READ_ACCESS_TOKEN if (!READ_ACCESS_TOKEN) throw "themoviedb.org READ_ACCESS_TOKEN not found in environment variables" const moviedbProps = { baseUrl: 'https://api.themoviedb.org', baseImagePath: 'http://image.tmdb.org/t/p/w185/'
} const VIEWS_PATH = './app_api/views/' const views = { VIEW_LANDING: `${VIEWS_PATH}landing.pug`, VIEW_MOVIE: `${VIEWS_PATH}movieView.pug`,
} api.get('/', async (req, res) =&gt; { try { let rootTag = loadTemplate(views.VIEW_LANDING, {}) let response = Response.fromTag(rootTag) res.json(response.toJSON()) } catch (e) { console.log(e) res.status(500).json({ success: false, message: 'server error' }) }
}) api.get('/movie/:id', async (req, res) =&gt; { let movieId = req.params.id try { let data = await request(urlJoin(moviedbProps.baseUrl, `/3/movie/${movieId}`), { json: true, headers: { 'Authorization': 'Bearer ' + READ_ACCESS_TOKEN } }) if (data.poster_path) { data.poster_path = urlJoin(moviedbProps.baseImagePath, data.poster_path) } let rootTag = loadTemplate(views.VIEW_MOVIE, data) let response = Response.fromTag(rootTag) res.json(response.toJSON()) } catch (e) { console.log(e) res.status(500).json({ success: false, message: 'server error' }) }
}) module.exports = api
/*
* Here we set the a path to the landing.pug file
*/
const views = {
VIEW_LANDING: `${VIEWS_PATH}landing.pug`,
VIEW_MOVIE: `${VIEWS_PATH}movieView.pug`
}
/*
* The api's base path is called when users hit our app
* for the first time. We'll use the onemsdk to parse the
* pug file and generate the raw JSON response
*/
api.get('/', async (req, res) => {
 try
 {
let rootTag = loadTemplate(views.VIEW_LANDING, {})
let response = Response.fromTag(rootTag)
res.json(response.toJSON())
}
catch
 (e) {
console.log(e)
res.status(500).json({ success: false, message: 'server error' })
}
})

/routes/index.js also contains a route for the movie view page, when the user clicks on a movie title, the ONEm Framework will issue an HTTP GET callback to the href associated with that option, eg in landing.pug we have the following line:

a(href='/movie/76341/') Mad max

Later in this tutorial, we will tell the ONEm Framework to use the base path of /api, which will eventually translate into HTTP GET /api/movie/76341 when the user selects to view Mad Max.

Ok, so a quick recap. We have created two views using pug. Our web server is ready to accept callbacks from /api and /api/movie/{:id}

So what’s remaining now is to complete the setup of our micro-app.

Create a .env file in the project root path:

PORT=3000
READ_ACCESS_TOKEN=<themoviedb API Read Access Token (v4 auth)
2. We’ll use ngrok to give us a publicly accessible url to our Micro-app at localhost:3000.
ngrok http 3000

Copy the link provided by ngrok, it will be something like https://6f1ca0d4.ngrok.io

3. In the ONEm Developer Portal, select “Create App” and set the callback path to your app appending /api to the base path, eg: https://6f1ca0d4.ngrok.io/api

4. In the ONEm Developer Portal, select your new app and then select “Web channel”. Copy/paste the javascript code shown in the tab, into the body section of the /public/index.html of your Micro-app:

...
<body>
<h1>Movie micro-app</h1>
<script src="https://bot.onem.zone/bundle.js"></script>
<script>
ONEmStart({ app_id: "5eb948e62d60d1001f32fb83" }).render('body');
</script>
</body>

Tip: This code snippet can be included in any website, if you have access to another website’s index.html, then go ahead and try it.

Running

Fire up your micro-app:

$ node index

In your browser, visit localhost:3000 (or where ever your app is configured to listen).

The ONEm Micro-app should be visible in bottom right-hand corner. Click the icon to open.

You can also view the SMS client from the developer portal test client. After registering your mobile number, you can test out the SMS interface by entering # followed by your micro-app name in the input box.

No tags for this post.

Related posts

Making the Best of a Less-Than-Ideal Remote Work Environment

I recently wrote a blog post about perfecting your remote work setup with lights, mics, and cameras. I took a deep dive into a very small segment of the remote work puzzle: getting your audio, video, and lighting good.

Today, worrying about those things feels pretty luxurious. In light of the number of companies moving (temporarily?) to work-from-home due to COVID-19, I sent out this tweet this weekend:

I’ve already received quite a few messages that go basically like this:

My company is suddently remote and we’ve never done this before. Help!

Like I wrote in the tweet, we’ve been remote for almost a decade, and tried almost every tool and trick you can imagine. There are so many aspects of this to cover. Here are a few places I’ve talked about remote work in the past (check the time stamps—some of them are a few years old)

But what I want to talk about today is the other side of my previous blog post. That post was about how I’ve spent years working on getting my not-at-home remote office just the way I want it.

Today, I want to talk about remote work—especially right now, as so many people are unexpectedly being told/allowed to work from home—and how so much of it happens in less-than-ideal environments, and what we can do to make the best of it. I’ll assume you’re working from home, but many of these tips apply in other less-than-ideal remote work environments as well.

What’s the ideal for remote work?

If I’m working remotely, I want these things:

  • Schedule and structure
  • Isolation when I want it
  • Social connection when I want it
  • A perfect computer setup
  • A perfect audio and video setup
  • Excellent communication channels
  • My kids somewhere else, having a great time and learning
  • A clean room
  • Exercise
  • Healthy food, when I need it

I’ve got most of these things in my normal day-to-day remote work. I pay for an office in a coworking space that’s a few minutes from my son’s school, and during the day my kids are at school or with their mom.

I’ve got a great tech setup, a stocked refrigerator and great restaurants nearby, my room is clean and isolated, and there are other folks around when I want to see them.

However, at least for the next few weeks, I, and millions of others, will be working from a place that likely hasn’t been set up to perfection. Me? I’m working from our spare bedroom—also known as a room with no desk—bad light, and a lot of junk. Plus, it’s just a dozen feet away from where my kids are playing all day. I need to get my stuff together, and you may too, so let’s talk about it.

Note: I’m going to do my best to give this advice assuming you don’t have kids, and then talk about kids at the bottom.

Structure

The most important thing that disappears when you start working from home is structure. There are a lot of structures we get from going into an office: time structures, physical structures, even management structures. These structures’ sudden disappearance don’t turn us into freeloaders who watch Netflix all day while getting paid for it, but it does add stress and uncertainty that can weigh on us.

🌟 Tip: Make a schedule

Schedules are our best tool to create structure. I use my calendar to plan out my entire day, both during the work hours (write for an hour, pair program for an hour, meeting for an hour, etc.) and also outside of the work hours.

Folks at Tighten, the consultancy I run, who always work from home told me to be sure to mention the daily routines that start and end our days. Wake up, run, take a shower, eat breakfast, get dressed, start work. Close laptop, turn off the lights, take a walk, start dinner prep. Whatever works for you, make a plan.

The consistency, regularity, and predictability will bring much of that structure you miss. And managing those transitions can often be the most important thing for controlling your stress in a less-than-ideal environment—this is what helps set those boundaries between “home” and “work”.

🌟 Tip: Set aside a space for work

Another great tool for creating boundaries between your work and personal life is to try to make a dedicated space for your work.

Obviously it’d be great if you had a home office, but if not, you may be able to carve out a space that’s entirely dedicated to work. This might be one end of the kitchen table, a certain corner of your bedroom, a desk in the living room, the garage, or anything else.

Make that, for now, your work space. Your computer lives there, your work gets done there, and most importantly, when you put yourself in that place you’re “at work” and when you leave that place you’re not “at work” anymore.

🌟 Tip: Get dressed for work (be like Mister Rogers)

You might be surprised, but getting dressed specifically for work has really powerful effects.

First, you’ll feel more mentally put-together when you’re not in your pajamas.

Second, this is another boundary you’re building between home and work, sort of like Mister Rogers changing his shoes when he gets home.

And third, you’ll be much less averse to video calls—I’ll talk about their importance later—if you’re looking professional.

But here’s another pro tip: keep a nice shirt and a hat nearby. That way, if you have to jump on a video call and you are wearing that one t-shirt you’re a bit embarrassed by, or you haven’t had time to do your hair today, you can just throw those things on and be ready for a call.

🌟 Tip: Pomodoros

If you’ve never worked with them before, a “pomodoro” is basically a period of work (often 25 or 50 minutes) followed by a period of rest (often 5 or 10 minutes). This is a way to build little micro-structures into your day, which can be especially helpful if you’re used to a day that’s not just sitting in front of the same computer at the same desk for eight hours.

Note: The actual Pomodoro technique is a bit more complicated than this recommendation, but when folks talk about pomodoro, they often just mean “period of work followed by a period of rest with a timer helping you remember”.

Equipment & Video

My last post was about my perfect setup I have at my office, which is pretty useless right now when I’m sitting at home. I have no desk, a Macbook Pro, and some headphones. Not the same. What can we do to improve our working-at-home equipment situation?

🌟 Tip: Noise-canceling headphones

This is an obvious one, but I’ll just throw it in here. Noise canceling headphones are so key when there are neighbors, kids, roommates, spouses, pets, or whatever else constantly vying for your attention.

“Less-than-ideal” work situations almost always have some element of distraction, and noise-canceling headphones and some chill background music can make a huge difference.

I personally saved up for Bose QC-35IIs a few years back, but those are $350 headphones. However, a few folks—including the Wirecutter—recommend the $60 Anker Soundcore Life Q20s.

🌟 Tip: Use a separate keyboard

Using a separate keyboard provides a lot of benefits when you’re not working from your perfectly-crafted office. Separate keyboards are likely to be more ergonomic than your laptop keyboard, they give you more flexibility to put your laptop in the right spot for good posture, and they help with video angles (more on that later.)

If you’re on a Mac, the Microsoft Sculpt Keyboard is incredible, and if you’re on Windows, the Microsoft Surface Keyboard is even better.

🌟 Tip: Sit up

If you can sit in a real chair, do it. One common component of less-than-ideal work environments is the lack of a desk. I know it might seem fun to work from the couch, but your back will make you feel it after a few days. If you’re working from a laptop, you can even possibly put your computer on a dresser and work standing up for segments of the day.

🌟 Tip: Video is best

This may seem crazy, because I think we’ve all see that news anchor working from home whose adorable children bust in on him, but when you’re working remotely, video calls—not just for group meetings but also for one-on-one conversations—give an opportunity for human connection and communication that is hard to get with audio or text.

This is a bit controversial, but I believe that every meeting I ever have with anyone should be video. Even in your less-than-ideal work situation, which often translates to less-than-ideal video environment, I encourage you to consider it.

🌟 Tip: We look worse from below

Quick webcam tip! When your webcam is mounted on the top of a laptop that’s on your lap, you’re going to get both a bad angle—your chin smushed down and a bit of a view of the underside of your nose—and bad lighting. Overhead lighting is bad for us anyway, but your face will look especially dark if you’re leaning over a bit to look into your webcam.

If possible, put your laptop on a desk or a stand and use a separate keyboard. This will both be better for your back and it’ll get you a better angle on your webcam.

🌟 Tip: Get some (side) light

Overhead light is not flattering. Most rooms have overhead light. However, it’s good when working from home to have plenty of light just for your emotional health, and most lights you could add to your room will not be at ceiling height.

Kill two birds with one stone: get some freestanding or desk lamps and put them near you. You’ll have a brighter work space and get better light for video.

🌟 Tip: Consider the background

When you’re on a video call, you’re exposing your less-than-ideal work environment to the world, right? That messy bed that’s been annoying you all day and making it hard to focus is now also in frame for all of your coworkers to see.

Some big things to watch out for:

  • Any kind of mess
  • Bright lights (shooting against a window will make you look like a mystery guest)
  • Unexpected guests (don’t put the bathroom door behind you or your spouse might get an unpleasant surprise)

I’ve seen folks put up privacy screens behind them to block out the view, and I think that’s a pretty advanced tip. For now, I just work with a wall behind me. It’s not pretty, but there are no naked people or dirty underwear on my wall, so I’ll call it a win.

Health

I won’t say that working from home is necessarily worse for your health than working at an office. There are some huge benefits, including access to family and comfort and removing a commute and removing interactions with potentially plain-old-cold-or-flu-sick coworkers.

However, there are a lot of distractions and possibly negative influences at home, and a lot of our healthier habits like healthy food at work and going to the gym might be disrupted if we’re working from home, especially during this particular moment.

🌟 Tip: Sit up

I wrote this above with regard to equipment, but I just want to say it again. Good posture is key. Your back is going to kill you if you work hunched over all day for weeks.

🌟 Tip: Take walks

Fresh air and sunlight and moderate physical exercise are three of the most important factors for our physical and mental and emotional health, and both fresh air and sunlight help kill germs and viruses.

🌟 Tip: Get natural light

Our minds and spirits respond better to natural light. Try to work in a place where there’s as much natural light as possible. If you suffer from Seasonal Affective Disorder, this may be the time to consider getting that artificial sunlight machine if you don’t have a window near you.

🌟 Tip: Limit trips to the kitchen

One way working from home can seem very ideal is access to the kitchen. Finally, you think, I can cook my own home-made meals! This is true, and often it can lead to much healthier eating.

However, easy access to the kitchen also can increase snacking, which, at a time you might suddenly be going to the gym less, is not ideal.

Consider scheduling your trips to the kitchen. Once for a morning snack, once for lunch, and once for an afternoon snack. Make sure you have snacks available that are healthy, and if not, train yourself to get water instead.

🌟 Tip: Meditate

You may be tempted to replace your commute with more entertainment time, or more work time. Consider instead setting aside time for you and your body. Meditate, or run, or walk, or whatever it is that gives you peace. Especially if you can do that at the start of the day, it could be a huge help for your less-than-usual days going more smoothly.

🌟 Tip: Keep up with mental health care

If you’re going to therapy, and you’re reading this article because of COVID-19, you may be unable to visit your therapist physically. Contact your therapist now and see if they offer telehealth (e.g. Skype calls).

Making drastic changes to your work context can have a big impact on your mental health, especially if it’s during a national crisis. Stress, anxiety, depression, relational conflicts—they’re all going to come to a head.

Many people have joked about how many new babies will come out of this time, but I also think there will be new fights, new divorces, new anxiety attacks, and much more. Take care of yourself, however you do that.

Relationships

Our friendships and family relationship are both key to our mental health when things aren’t going well, and also a possible source for things to be very tough when we’re all of a sudden crammed together in the same space.

🌟 Tip: Keep up your relationships

Working from home, especially when you didn’t chose it, can often feel very isolating. It can be helpful to intentionally keep rhythms and connections in relationships that you have in normal life.

Do you always catch up with one friend at lunch at the office? See if you can chat over Skype or Hangouts or whatever some lunch times. Always get together with your best friends at the bar every Tuesday night? Do the same thing, but over Hangouts. Each of you has their own separate drink, but you’re still together and still connecting.

I just happened to stumble across an article Wirecutter wrote about How to be Social While Social Distancing, and it’s also got some great tips there.

🌟 Tip: Set boundaries with your housemates

While your work and friend relationships may decrease, some other relationships will have increased access when you work from home, and this isn’t always good for the relationship. Especially if it’s during a time of stress, and especially if you have a smaller house, you’re going to start feeling the stress of your interactions with the folks you love.

One of the best tricks we’ve come up with as from-home workers is to be very clear about our boundaries (but still gracious when they’re broken). Many folks will make a “at work, do not disturb” sign they can hang on a door, or create a “if the door is closed, I’m working” policy. Others may choose hours: “Between 9-12 and 1-5 I’m in work mode”.

The best way to avoid conflict is to express your unspoken expectations. Do you expect not to be interrupted when you’re working? Say it, kindly. Remind it, kindly, if it happens.

Grace

Speaking of grace… grace is a key component of working from less-than-ideal situations.

🌟 Tip: Give others grace

If this situation is less than ideal, it’s likely either new, or cramped, or something else that makes it less than ideal not just for you but also for the people around you. When your housemate unthinkingly plays loud music or your spouse asks for your help with something or your kid asks you to look at their painting, they’re not trying to mess up your work flow. Give them grace.

Of course, giving someone grace is not the same as a free pass. You can still be direct and clear while being gracious and loving.

🌟 Tip: Give yourself grace

Most importantly, recognize that you’re not going to be able to produce quite the same amount or quality of work when you’re first entering a less-than-ideal remote working scenario. You’ll get there. But it takes time.

Don’t get mad at yourself for being distracted. You’re going to get distracted. Your kids or housemates or spouse or cat merit your love and attention and sometimes those things don’t happen in the timing you wanted. You’re a human being and you’ll respond as a human.

Give your systems and structures space for grace. Don’t build something so rigid that, if you decide to take the cat for a walk at 2pm, the rest of your day falls apart. That’s not a failure! That’s a healthy and normal part of human life, and one which any structure needs to allow.

Take an attitude toward yourself that you’re doing the best you can with what you have and you’ll get a little bit better every day. That’s all anyone can ask of you.

Kids

So, I’m going to rely on other folks a bit here. I do have two children. However, my wife’s career field is mainly on hold because of COVID-19, so she’s primarily taking care of the kids while I work. So, unlike families where both spouses work, or single parents, I have it much easier. My main concern with the kids is not having to be fully responsible for their safety and feeding and education, but just enjoying them without being too distracted by them.

However, if you have kids—especially young kids—and you’re responsible for them during this time and have to do a job, you’re in the hardest of non-ideal work settings. Here are some ideas I’ve had, along with a few from friends.

🌟 Tip: Make a schedule

Kids thrive on structure, despite how much they say they don’t like it. Make a daily schedule for their education, food, play, screen time, and whatever else. Keep it flexible, keep it gracious, but make it clear so they can know what to look forward to.

This will also help you, as it’ll become easier to know when to schedule meetings, and easier to let them have some screen time or play time without feeling like a terrible parent.

Pro tip: If your kids are old enough, involve them in creating the schedule!

🌟 Tip: Screens aren’t evil

Sure, you read all those articles about how kids are going to melt their brains on screens. Screw that shit.

Your kids are not the only people in your house who matter. Your work, your time, and your sanity are also important. Use the tools you have available to you—which include educational screens and even non-educational screens—to make the best of the situation you’re in. End of story.

🌟 Tip: Work while they play

All of us have some busy work, and I’ve found that I can work through the busy work while my kids play. That means if I want them to play outside (my kids are young and we don’t have a yard, so I have to supervise them when they play outside), I could take them outside, sit on my laptop, and work through emails while watching them play soccer out of the corner of my eye.

Life doesn’t always have to be binaries. Working or home. I do think boundaries are healthy, but sometimes, especially with kids, you gotta do what you gotta do.

🌟 Tip: Involve them

If your less-than-ideal work environment is your home, there are likely other tasks that are occupying your day as well: laundry, cooking, cleaning. These tasks often require us to put the kids in front of screens for yet another half hour, but there’s an incredible alternative: involve your kids in the housework.

Get your kids to put away the laundry. Have them stir the sauce. Teach them how to clean windows and dust. They’re both learning valuable skills, they’re shaking off some entitlement to being entertained, and, if they’re old enough, they might even help you out!


Not the end

That’s all I’ve got for now. I’ll be happy to update this post as more suggestions come in.

I’m pretty active on Twitter as @stauffermatt, so please feel free to ask me questions there, and I also have a YouTube channel and one thing folks do there is ask me questions that I answer in short video format, so if you shoot me a question on Twitter or in a YouTube comment, I might get a chance to address it there.

Thanks so much for reading. Remember: grace to you. Grace to your family. We’re going to get through this.

No tags for this post.

Related posts