Click here to Skip to main content
15,505,409 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am currently doing a user sign up interface using javascript. However I am unsuccessful to establish a cookie session.

After singing up in the localhost network, it prompt this message --> site cant be reach. localhost refuse to connect.

I have re-intsalled the cookie-session package but it is still not working

Is there anyway to make it work?

here is the error message from terminal: (node:7978) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined at /Users/gabrielswee/Desktop/Desktop Folders/Courses/Javascript/ecomm/index.js:58:29 (node:7978) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see (rejection id: 1) (node:7978) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Here is my syntax


const express = require("express");
const bodyParser = require("body-parser");
const cookieSession = require("cookie-session");
const usersRepo = require("./repository/users");

const app = express();

//NOTE: Middleware: To automatically body parse the data

    extended: true

//NOTE: Middleware: Cookie Session

        name: "session",
        keys: ["lucky6226"]

//NOTE: User Sign Up
app.get("/", (req, res) => {
    Your id is:${req.session.userId}
    <form method ="POST">
    <input name ="email" placeholder="email" />
    <input name ="password" placeholder="password" />
    <input name ="passwordConfirmation" placeholder="password confirmation" />
    <button>Sign Up</button>

//NOTE: Validating User Email and Password"/", async (req, res) => {
    const {
    } = req.body;

    const existingUser = await usersRepo.getOneBy({

    if (existingUser) {
        return res.send("Email in use");

    if (password !== passwordConfirmation) {
        return res.send("Password must match");

    //NOTE: Create users in the user repository
    const user = await usersRepo.create({

    //NOTE: Store ID in the cookie. Use 3rd party package for Cookies --> npm install cookie-session
    req.session.userId =; //Add by cookie session

    res.send("Account Created !!!");

//NOTE: HTTP Request
app.listen(3000, () => {
    console.log("Connection established successfully");


const fs = require("fs");
const crypto = require("crypto");

class UsersRepository {

constructor(filename) {
    if (!filename) {
        throw new Error("Creating a repository requires a filename");

    this.filename = filename;

    try {
        //NOTE: Check to see if the file exist
    } catch (err) {
        //NOTE: if file do not exists, create the file
        fs.writeFileSync(this.filename, "[]");

async getAll() {
    return JSON.parse(
        await fs.promises.readFile(this.filename, {
            encoding: "utf8"

async create(attrs) { = this.randomId();
    const records = await this.getAll();
    await this.writeAll(records);

async writeAll(records) {
    // NOTE: Write the updated 'records' array back to this.filename
    await fs.promises.writeFile(
        JSON.stringify(records, null, 2)

randomId() {
    return crypto.randomBytes(4).toString("hex");

async getOne(id) {
    const records = await this.getAll();
    return records.find(record => === id);

async delete(id) {
    const records = await this.getAll();
    //NOTE: Return true if ID is not the same

    const filteredRecords = records.filter(record => !== id);
    await this.writeAll(filteredRecords);

async update(id, attrs) {

    const records = await this.getAll();
    const record = records.find(record => === id);

    if (!record) {
        throw new Error(`Record with id ${id} is not found`);

    //NOTE: Assign attrs {password} (attributes) into the record {email}
    Object.assign(record, attrs);

    //NOTE: Outcome --> record === {email: '', password: 'mypassword'}
    await this.writeAll(records);


async getOneBy(filters) {

    const records = await this.getAll();
    //NOTE: outer for of loop --> looping through an array
    for (let record of records) {
        let found = true;
        //NOTE: inner for in loop --> search an object

        for (let key in filters) {
            if (record[key] !== filters[key]) {
                found = false;

        if (found === true) {
            return record;


//NOTE: File export

module.exports = new UsersRepository("users.json")

What I have tried:

I tried retyping and reinstalling the node packages but it did not work
Updated 5-May-20 21:42pm
Kornfeld Eliyahu Peter 9-Jan-20 9:55am    
You should debug your code...
Based on the information 'user' (here: req.session.userId =;) is undefined...
It may has something to do with you work with async/await...

1 solution

You need to return attrs from the end of create() in users.js. That's how gets usersRepo attrs to assign to req.session object in index.js.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900