Author: Omer Goldberg

Web Cookies for Everyone

Web Cookies for Everyone

Web jargon! It’s hard to keep up at times. The worst is when terms that are supposedly simple are thrown around, and you just sit there at the meeting like this.

Web cookies is definitely one of those terms. The purpose of this post is to explain web cookies in a simple manner. We will focus on the core concept, so that you can later apply this in any project, regardless of which framework or library you may choose. At the end of this post you should be able to differentiate between an actual cookie and a web cookie pretty confidently 😉

Cookies?!? What do you mean

A web cookie is a small bit of text that is sent to your browser by a server. A cookies purpose is to carry bits of useful information about your interaction with the website that sets them. The browser may store it and send it back with the next request to the same server. This way, the server can distinguish whether two requests came from the same browser.

Cookies are specific to a web browser. Therefore, if you use a different computer, open a different browser or delete your cookies, the website will treat you as if you have arrived for the first time (and a new cookie will be set).

What are cookies used for?

Cookies can be used for a variety of reasons:

  1. Remember your settings on a website. Like whether you read the oldest or newest comments first; the volume on the video player, how long you hovered over a specific post, your shopping carts state, game scores and more.

2. To understand how you and other users are using the site. For example, to tell what the most popular news story of the day is. Or to tell how badly you want an airline ticket. Evilness!

3. Authentication services like logging in to a service or to make sure you’re logged in securely (these cookies may contain information such as your email address and your name — the information you gave when you signed up. The website you signed up to is the only site that can access this information.)

Cookies in Practice

Let’s start seeing things in action by setting our first cookie and examining it in the browser.

It’s important to note that the Chrome browser won’t store cookies set from local web pages. Therefore we’ll set up a simple node server that will allow us to work under the localhost domain. To get this working locally clone the repo from this github repo, and run npm install. Then navigate to project directory and run

Call it maaagic
const express = require('express')
const app = express()

app.get('/', (req,res) => {
  res.sendFile(__dirname + "/index.html");
})

app.listen('8081')
console.log('Magic happens on port 8081')
exports = module.exports = app
Simple Express Server

Great! Now that we have our local dev environment setup and we can start playing with cookies.

Let’s work towards something that resembles a real life scenario. Say we want to create a site that upon a users first visit prompts him/her for his name. When the user enters his name, we’d like to save it (via a web cookie), so that on the user’s next visit we can give them a warm welcome 🙂

Here’s the basic markup we’ll be using for this experiment:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1>Cookies!</h1>
    <button>Show cookies</button>
  </body>
</html>

Let’s start off with setting and getting a cookie in it’s most basic form.

 <!DOCTYPE html>
<html>
<head>
  <script>
    document.cookie = "monster=cookie";
    document.cookie = "favorite_food=chocolate_chip";
    alert(document.cookie);
   </script>
</head>
<body>
  <h1>Cookies!</h1>
</body>
</html>

Now let’s restart the server so we can see the new changes. Voila!

Our snazzy alert message
Viewing cookies via Chrome Developer tools

So when we show our document’s cookies we get something almost exactly identical to what we set. What’s the subtle difference? See that semi colon between both key-value pairs? Hmm.. we didn’t explicitly set that. So this is an example of how the browser differentiates between different cookies. By adding a semi colon to it!

Methods for fetching, setting and checking for cookies

Alright, alright. So at this point we’ve seen that cookies are built right into the global document object. We can set them by passing a string key-value pair to document. cookie. We can view all of our current web pages cookies by accessing document.cookie. Let’s try and build a more scalable approach to getting and setting cookies by creating some Javascript methods.

Like we saw in our mini example above, cookie are saved as a string and separated by semicolons. Therefore we are going to use some built in Javascript string methods to fetch our cookie.

fetchCookie()

Our first method will check our cookies for a cookie with the username key and returns it if it exists.

const fetchCookie = () => {
  const name = "username" + "=";
  const cookie_array = document.cookie.split(';');
  for(let i = 0; i < cookie_array.length; i++) {
      let c = cookie_array[i];
      if (c.indexOf(name) == 0) {
          return c.substring(name.length, c.length);
      }
  }
  return "";
}

getUserData()

This method will check the browser for a cookie with a “username” key. If it exists we will welcome the user. Otherwise we will prompt him/her for their name.

 const getUserData = () => {
  let username = fetchCookie();
  if (username != "") {
    alert("Welcome again " + username);
  } else {
    username = prompt("Please enter your name:","");
    setCookie("username", username, 30);
  }
}

setCookie()

Our setter method will accept 3 params. A key, a value, and an expiration date.

 const setCookie = (key,val,days_till_expiration) => {

  let d = new Date();
  d.setTime(d.getTime() + (days_till_expiration*24*60*60*1000));
  const expires = "expires=" + d.toGMTString();
  document.cookie = key + "=" + val + ";" + expires + ";";
}

The Final result

Wrapping up

Cookies are a big part of web development and are something we use everyday as consumers. Hopefully knowing how this works on the development side gives a little more insight into the inner workings of some of your favorite websites.

In case you want a big picture view, here is the full code available on our GitHub account.

Feel free to follow me on LinkedIn or Github where I regularly post entrepreneurship and tech related content.

At CodingStartups. We’re building a community of builders with an emphasis on teaching skills that help you get stuff doooone. Subscribe!

Until next time ✌️

Command & Conquer: Startup Law Essentials

Command & Conquer: Startup Law Essentials

Command & Conquer: Startup Law Essentials

JoiRyde, my startup, had failed…but the mourning period was over. It was time to come back — smarter, faster and stronger than before.

I began the post mortem and quickly realized that one of our glaring mistakes was lack of legal structure. Looking back, my co-founders and I preferred focusing on what was easiest for us — the code. The legal ins and outs were tricky, and we delayed them until it was absolutely necessary (and too late!) Never again; I decided it was time to educate myself.I sought counsel with my friend Idan Bar-Dov. Idan is a lawyer who specializes in startups and if Suits was real, this guy would be Harvey.

In this post, we try to demystify complex legal terms and clarify key issues usually encountered when starting your own company.

Just so we’re clear: This post is intended for informational purposes only and does not constitute legal advice.

Company 101

Ha! I know what you’re thinking! “I know what a company is dude … get to the goood stuff”.

Though we intuitively understand what a company is, its legal definition is quite different from what we know.

There are different kinds of companies. However, in the context of the startup world, when someone says “I just started my own company”, it usually means that they have incorporated a private for-profit organization. In other words, it’s a privately-operated legal entity intended for financial gain.

Legally speaking, a company is independent. It can enter into agreements, assume obligations, and be held accountable for its actions. Incorporators may share a great deal of interest with their company, but legally they are not the company. The employees, founders, board members, and even the CEO are all a part of the company, but combined do not equate the company itself.

Nevertheless, companies are run by people. Like a ship, steered by the captain and crew, companies are lead by their Board of Directors and operated by the people who control the “Company Organs”. These include shareholders, directors, officers etc., who affect the decision-making processes at their different capacities.

They’re on a boat

The Upside (and its limit)

Founders are usually the individuals who “give birth” to the company. They fill out the paperwork, pay the incorporation fee and sign the relevant documents.

In this context remember the following rule of thumb: No Registration = No Incorporation! Namely, your Company registration must be approved by the state.

The main benefit of incorporating is gaining a distinction between individual and company — a.k.a. a “corporate veil”. As separate legal entities, companies are accountable for their debts and obligations, as opposed to the individuals who operate them. In other words, each individual’s contribution marks the limit of their potential financial risk. Hence the term “limited liability company”.

However, the veil’s protection is not absolute. In certain cases Individuals may be held personally accountable for their actions. For example, when using a company for fraud, illegal actions, or to circumvent existing obligations.

Equity — Make it Rain

Crash course definition: equity = holdings, owning a chunk of the company.

Two co-founders splitting equity

When founders say equity they usually refer to shares. This is the company’s “currency”, which entitles its holders to certain privileges, such as financials, control, and information rights.

There is no gold standard in dividing equity between co-founders, it’s subject to your discretion. I believe that founders should be equal partners. Idan thinks that equity should reflect skill and contribution (Y Combinator has researched this extensively, you can read more here).

Exodus — Founder departure

Once equity has been issued, a founder’s reason of departure won’t matter much. They are already an equity owner — it’s theirs, no turning back.

Such a departure may generate “dead equity”. Shares which are held by a founder who is no longer involved with the company. This creates an involvement-equity mismatch, which has negative impact, especially on the company’s fundraising front.

The solution is defining the founders’ relationship upfront, by entering into a Founders Agreement. A departure case must be addressed before it occurs, preferably even before incorporating. Think of a founders agreement like a prenup, which obviously should be signed before getting married.

Equity-wise, it is customary to include a “vesting schedule”, which determines the founders equity eligibility. The purpose of a vesting arrangement is to incentivize founders to remain engaged with the company and diminish any involvement-equity mismatch.

A standard time-based vesting schedule will specify that if a founder leaves before date X, then he will give-up Y equity. For example, in a linear 3 years vesting schedule, if a founder leaves after 1 year, then he gets to keep ⅓ of his shares, and has transfer the other ⅔ to the remaining founders. It’s a quid pro quo arrangement: work = equity.

Things to Remember

  1. Don’t procrastinate — Even it seems dull, take care of your legal foundations from the get go and don’t wait until it’s too late.
  2. Expectation Management- Defining the Founders’ relationship early on helps all founders see eye to eye.
  3. Attracting Investors — Even if your product or tech is extremely impressive, a neat legal duck is always a plus. It conveys awareness and shows investors you’re sincere, organized and devoted.
  4. Prevention is the best medicine — Building a company is an intense endeavor, and it can bring out a drastically emotional side of you. So set up defense mechanisms before taking-off with your team, when everyone is as clear-headed and calm as possible.

If you liked this article, feel free to share. You can follow Idan on Linkedin. You can follow me on Linkedin, Medium or Github for more technology / entrepreneurship content.