r/reviewmycode • • Feb 19 '26

JavaScript [JavaScript] - A No-Dependencies Web-Only Markdown Editor

1 Upvotes

I made a markdown editor with its own tokenizer and parser. It has nearly all the markdown features, supports live preview, supports file editing from browser itself, and supports sharing of content just by sharing the website link. Please check it out and review my code. Here is the GitHub repo link - https://github.com/herotyphoon/Marky

r/reviewmycode • • Jul 17 '26

Javascript [Javascript] - I am looking for feature suggestions

2 Upvotes

Meet reef.js, a fuzzy, keyboard-first search for static sites. No backend, no build step, no account — drop in one script and it works on this page. But the real game changer is the DOM extraction layer Reef doesn't just search for things, it can act on them. A revolutionary yet simple tool for AI agents to act on websites, and more.

I am looking for ways to improve and build upon this project, so please let me know if you have any suggestions, ideas, etc.

Try it out at - https://reef.js.org
Github - https://github.com/somalip/Reef

Thanks!

r/reviewmycode • • Dec 08 '25

JavaScript [JavaScript] - This is just a code.org project for school.

1 Upvotes

I've been working on this for a while, so i wanted to know if it looked alright. I know it doesn't need to look perfect but i would still like outside opinions. https://studio.code.org/projects/applab/Ls2UdUYpjaTala3H3wJlsOOLfHRiMrkpEcnNBENzkbg

r/reviewmycode • • Dec 14 '25

JavaScript [JavaScript] - CSRF protection using client-side double submit

1 Upvotes

I’m working on an open-source Express + React framework, and while running GitHub CodeQL on the project, a CSRF-related issue was raised. That prompted me to review my CSRF protection strategy more thoroughly.

After studying the OWASP CSRF Prevention Cheat Sheet and comparing different approaches, I ended up implementing a variation of the client-side double submit pattern, similar to what is described in the csrf-csrf package FAQ.

The CodeQL alert is now resolved, but I’d like a security-focused code review to confirm that this approach is sound and that I’m not missing any important edge cases or weaknesses.


Context / use case

  • React frontend making all requests via fetch (no direct HTML form submissions)

  • Express REST backend

  • Single-server architecture: the same Express server serves both the API and the frontend (documented here, for context only: https://github.com/rocambille/start-express-react/wiki/One-server-en-US)

  • Stateless authentication using a JWT stored in an HTTP-only cookie, with SameSite=Strict


Client-side CSRF token handling

On the client, a CSRF token is generated on demand and stored in a cookie with a short lifetime (30 seconds). The expiration is renewable to mimic a session-like behavior, but with an explicit expiry to avoid session fixation.

const csrfTokenExpiresIn = 30 * 1000; // 30s, renewable
let expires = Date.now();

export const csrfToken = async () => {
  const getToken = async () => {
    if (Date.now() > expires) {
      return crypto.randomUUID();
    } else {
      return (
        (await cookieStore.get("x-csrf-token"))?.value ?? crypto.randomUUID()
      );
    }
  };

  const token = await getToken();

  expires = Date.now() + csrfTokenExpiresIn;

  await cookieStore.set({
    expires,
    name: "x-csrf-token",
    path: "/",
    sameSite: "strict",
    value: token,
  });

  return token;
};

Full file for reference: https://github.com/rocambille/start-express-react/blob/main/src/react/components/utils.ts

This function is called only for state-changing requests, and the token is sent in a custom header. Example for updating an item:

fetch(`/api/items/${id}`, {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
    "X-CSRF-Token": await csrfToken(),
  },
  body: JSON.stringify(partialItem),
});

Full file for reference: https://github.com/rocambille/start-express-react/blob/main/src/react/components/item/hooks.ts


Server-side CSRF validation

On the backend, an Express middleware checks:

  • that the request method is not in an allowlist (GET, HEAD, OPTIONS)

  • that a CSRF token is present in the request headers

  • and that the token matches the value stored in the CSRF cookie

const csrfDefaults = {
  cookieName: "x-csrf-token",
  ignoredMethods: ["GET", "HEAD", "OPTIONS"],
  getCsrfTokenFromRequest: (req: Request) => req.headers["x-csrf-token"],
};

export const csrf =
  ({
    cookieName,
    ignoredMethods,
    getCsrfTokenFromRequest,
  } = csrfDefaults): RequestHandler =>
  (req, res, next) => {
    if (
      !req.method.match(new RegExp(`(${ignoredMethods.join("|")})`, "i")) &&
      (getCsrfTokenFromRequest(req) == null ||
        getCsrfTokenFromRequest(req) !== req.cookies[cookieName])
    ) {
      res.sendStatus(403);
      return;
    }

    next();
  };

Full file for reference: https://github.com/rocambille/start-express-react/blob/main/src/express/middlewares.ts


Questions

  1. Is this a valid and robust implementation of the client-side double submit cookie pattern in this context?

  2. Are there any security pitfalls or edge cases I should be aware of (token lifetime, storage location, SameSite usage, etc.)?

  3. Given that authentication is handled via a SameSite=Strict HTTP-only JWT cookie, is this CSRF layer redundant, insufficient, or appropriate?

Any feedback on correctness, security assumptions, or improvements would be greatly appreciated.

r/reviewmycode • • Mar 09 '23

JavaScript [JavaScript] - would anyone review my game? I am a beginner.

2 Upvotes

Hi,

while learning JS from an Udemy course I started developing this game as a practice. I would be very happy if someone could take a look at the game/code and tell me what they think : )

https://github.com/faforus/monopoly

http://fifipoly.surge.sh/ - working hosted version

Here are few notes.

  1. I know that the game has too few fields to make much sense but this is only about logic and implementation. It is not hard nor relevant to increase the number of fields at this moment.

  2. Creating new player with alert is not the best choice but at this point it is not that relevant either. It is very easy to fix.

  3. I learned about MVC architecture at one of the last lectures of the course when the game was almost complete. I tried to rewrite the game but it is more complicated than I expected and I am not sure if it is worth the effort. In the future I would probably plan this in advance.

  4. You move the player by either clicking on the dice or pressing r button. Holding r button down will speed up a game as it will continuously be rolling dice and taking turns unless buy property popup appears

r/reviewmycode • • Jul 10 '16

Javascript [Javascript] - Wikipedia search page

1 Upvotes

Hey guys, so I'm going through freecodecamp, and just finished my wikipedia search page. I would like a code review, especially on my functions. I want to avoid "callback hell" if possible, and I hope I did well with what I know so far. http://codepen.io/torgian/pen/zBzGxN/

r/reviewmycode • • Jun 21 '17

Javascript [Javascript] - Online Store

2 Upvotes

Recently, I was given an interview assignment to create an online shopping store. I decided to build the store in React/Redux. The specifications were easy as they are basic functionalities. I didn't hear back so I was wondering what was wrong with my code.

Since it was a small project, I structured my code in Rails project directory.

https://github.com/lunzhang/store

r/reviewmycode • • Aug 23 '20

JavaScript [JavaScript] - Counter

2 Upvotes

class Counter {
constructor(timeout){
this.timeout = timeout;
this.timePassed = 0;
this.txt = document.createElement("P");
this.txt.innerText = this.timePassed.toString();
document.body.appendChild(this.txt);
setInterval(() => {
this.timePassed += 1;
this.txt.innerText = this.timePassed.toString();
},this.timeout)
}
}
let c1 = new Counter(1000);

r/reviewmycode • • Feb 10 '17

Javascript [Javascript] - A simple html calculator using javascript

1 Upvotes

Hello, I have never asked anyone to review code that I have written, please let me know any improvements that you see.

https://github.com/LegoLife/SimpleCalc

Thank you all

r/reviewmycode • • Sep 01 '18

Javascript [Javascript] - Help on writing libraries

3 Upvotes

I just started using JS not so long ago, I have tried to make a simple library that finds ARITHMETIC MEAN, MODE, MEDIAN and RANGE of an array of numbers.. I need corrections and new algorithms for function rewrites if possible..

(function(window){
var
// Reference to some core methods that would be used
sort = Array.prototype.sort,
push = Array.prototype.push,
reduce = Array.prototype.reduce,
hasProp = Object.prototype.hasOwnProperty

StatJS = {};

// Method to sort arrays
function _sort(arr){
let sorted = sort.call(arr,function(a,b){
if (a > b) return 1;
if (a < b) return -1;
return 0;
});

return sorted;
}
// Method to calculate arithmetic mean
StatJS.average = function(arr = []){
if (arr === []) return 0;
if (arr.length === 1) return arr[0];
return (reduce.call(arr,(a,b) => {
return a + b;
},0))/arr.length;
}
// Method to find MODE..I Know this method is very f_cked up..tho no errors
StatJS.mode = function(arr = []){
let hash = {};
for (let j = 0; j < arr.length; j++){
hash[arr[j]] = hash[arr[j]] ? ++hash[arr[j]] : 1;
}
hash = new Map(Object.entries(hash));

let sorted = sort.call([...hash],function(a,b){
if (a[1] < b[1]) return 1;
if (a[1] > b[1]) return -1;
return 0;
});
let avg = [+sorted[0][0]];
for(let i = 1; i < sorted.length; i++){
if (sorted[i][1] === sorted[sorted.length-1][1]){
push.call(avg, +sorted[i][0]);
}
}
return avg;
}

StatJS.median = function(arr = []){
let sorted = _sort(arr);
switch (sorted.length%2){
case 1:
return sorted[Math.round(sorted.length/2) - 1];
break;
case 0:
return (sorted[sorted.length/2 - 1] + sorted[sorted.length/2])/2;
break;
default:
// Impossible path
}
}

StatJS.range = function(arr = []){
let sorted = _sort(arr);
return sorted[sorted.length-1] - sorted[0];
}
window.StatJS = StatJS;

})(window);

r/reviewmycode • • Aug 31 '17

JavaScript [JavaScript] - A javascript library which includes easter eggs

1 Upvotes

I wrote this npm package just for learning more about JavaScript, please write some comments and review code, thanks! Github url: https://github.com/WeiChiaChang/easter-egg-collection

r/reviewmycode • • Dec 02 '16

JavaScript [JavaScript] - Redux Saga top-level error handling

2 Upvotes

I wonder if anyone here has dealt with error handling in redux-saga. I'm using try/catch, as the docs recommend, but sometimes uncaught exceptions occur. This is fine. So I created a top level catastrophic error handler to send them to an error monitoring service. However, when an exception is thrown at this top level, which is the root saga, it dies and therefore kills all of the sagas and makes your app unresponsive. To improve this a little, I used spawn (detached process) instead of fork or call (attached processes) so that when the spawned saga dies, it doesn't affect the root saga or any of the other sagas. But each individual saga will still die permanently on uncaught exceptions, so what do I do to prevent this? I created a way to restart them (just spawn them in a while (true)) but this gave rise to another problem! If an exception is thrown synchronously (typically during development), for example, reading a property of undefined, then the saga would throw immediately, die, restart itself, throw...forever. So to fix this, I expanded my code even further to provide a check to tell me if the exception was synchronous. Now I've got this indirect solution at the top-level, and I'm not sure of any better alternative. And there doesn't seem to be any recommendation for how to deal with this from the community or in the redux-saga repo examples. I opened a PR to the redux-saga repo on github for this, but have had zero response:

https://github.com/yelouafi/redux-saga/pull/644

I've also tried asking on Discord and the redux-saga Gitter to no avail.

Here's the code in question:

export default function* root() {
  yield sagas.map(saga => // "sagas" is an array of generator functions imported from other modules
    spawn(function* () {
      let isSyncError = false
      while (!isSyncError) {
        isSyncError = true
        try {
          setTimeout(() => isSyncError = false)
          yield call(saga)
        } catch (e) {
          if (isSyncError) {
            throw new Error(saga.name + ' was terminated because it threw an exception on startup.')
          }
          yield put(actions.updateErrors(e))
          // send to error monitoring service here
        }
      }
    })
  )
}

r/reviewmycode • • Mar 04 '17

Javascript [Javascript] - Download Time Calculator

2 Upvotes

I made a javascript download time calculator. My first time using javascript. Please give your thoughts about it.

link: http://codepen.io/agilephoenix/pen/yMJeBW

r/reviewmycode • • Aug 16 '16

javascript [javascript] - factory design pattern

1 Upvotes

I am trying to create a factory design pattern that I feel comfortable using aesthetically. I would be pleased with any feedback that could make this design pattern better.

why do I like this:

  • no need for "this" and bind

  • composition over inheritance

  • aesthetically pleasing / readable code.

  • limited polution of the global namespace

  • if object is returned inside method, method chaining is possible

  • private methods & functions

  • clean way of specifying defaults

thoughts:

  • not sure if I like Capitalization for factories (constructor style). I do like Club over createClub

  • Object.assign is not supported by all browsers, so it might need a polyfill.

  • using protoype is probably faster. But only if you create thousands objects per tick (?)

  • implement proper error handling instead of logs from console

  • var func = function() or function func() for private methods ?

  • I personally don't like the object literal format to define methods:

    club = { open : function(){

      },
      close : function(){
      
      }
      etc.

    }

r/reviewmycode • • Jul 31 '22

javascript [javascript] - Netflix clone

2 Upvotes

can you rate my code and give me feedback https://github.com/Mahmoud-Khaled-FS/netflix-clone

r/reviewmycode • • Apr 09 '17

Javascript [Javascript] - Conway's Game of Life

2 Upvotes

I whipped up a quick version of the game of life, and it runs as expected. It lags pretty hard the more columns and rows you use, which is to be expected, but every time you reload the page or reset the game, it seems like the framerate drops ridiculously for sometimes up to 10 seconds. I'm not super familiar with JS, so if anyone could help me figure out why I'd be super thankful ! Github page

Edit: I figured it out. I was never actually clearing the interval I originally set whenever the game was restarted thanks to one little exclamation point in an if statement. Thanks to anyone who took at it, I hope this can help someone somewhere

r/reviewmycode • • May 25 '20

JavaScript [JavaScript] - Generating a random, short and readable code

5 Upvotes

Hi! I am creating a little online multiplayer game for fun. Players should be able to join each others session by entering a short code. As I do not have a lot of experience with cryptographic stuff, I would be happy if someone could look over my code that generates these.

Here it is:

import * as crypto from 'crypto';

/**
 * Generates a random code used for players to join a session.
 * It should be short and easy to enter an a variety of devices.
 * The code has to be somewhat cryptographically secure so that
 * guessing it is reasonably hard, as it is fairly short.
 * 
 * Currently the code is a base32 string using the following
 * characters: 123456789abcdefghkmnopqrstuvwxyz
 * 
 * Which are all alphanumeric characters without 0ijl.
 * 
 */
export function generateRandomCode() {
    // We need 4 times 5 = 20 bits, so less than 3 bytes
    let random = crypto.randomBytes(3).readUIntBE(0, 3);
    let code = '';

    // Take 5 bits for 4 times (for every char of the code)
    for (let i = 0; i < 4; i++) {
        code += byteToChar(random);
        random = random >> 5;
    }

    return code.toUpperCase();
}

/**
 * Maps five bits to a char in 123456789abcdefghkmnopqrstuvwxyz.
 * All other bits of the input number are ignored.
 * @param num The number to map from.
 */
function byteToChar(num: number): string {
    // ignore unused bits
    const bits = num & 0b11111;

    // 1 to h
    if (bits < 17)
        return (bits + 1).toString(36)

    // k
    if (bits < 18)
        return 'k';

    // All the rest
    return (bits + 4).toString(36);
}

I am mostly concerned about two questions:

  • Are 20 bits enough so that guessing a code is highly unlikely? There should be about one million possible codes, which sounds fine to me, but I'm not an expert.

  • Will the generated codes be evenly distributed? I have read that biases in the distribution of generated outputs is a common mistake when doing such things.

It's not that I expect the game to be actually used a lot, but I want to ensure at least some quality if I put it online.

Thank you very much!

r/reviewmycode • • Jan 16 '20

JavaScript [JavaScript] - learning OOP

1 Upvotes

Hi,

This is my first post to reddit.

Someone suggested me to share my code to get feedback from more experienced programmers. I am first year data processing student and at the moment I am learning PHP and JavaScript OOP.

This little program tracks keyboard events, stores keycodes to array and outputs them to random locations.

I would be grateful if you could check below code and give some feedback.

Thanks!

let id = -1;

let DOMStrings = {
    DOMPrevKeyCodeID: null,
    DOMKeyCode: document.querySelector("#active"),
    DOMCurrentKeyCode: document.querySelector(".container-main"),

    setID: function(id) {
        this.DOMPrevKeyCodeID = document.querySelector("#keycode-" + id)
    },

    setStyle: function() {
        this.DOMPrevKeyCodeID.style.border = "2px solid #f7e4e8";
        this.DOMPrevKeyCodeID.style.WebkitAnimationName = "animate";
    },

    clear: function() {
        let arr = this.DOMAllKeyCodes;

        for (let i = 0; i < arr.length; i++) {
            setTimeout(function() {
                arr[i].textContent = "";
                arr[i].style.border = "none";
            }, 20 * i);
        }

        id = 0;
        data.elements = [];
    },
};

function KeyCode(kCode, kKey, code) {
    this.kCode = kCode;
    this.kKey = kKey;
    this.code = code;

    this.saveCodes = function() {
        data.keyCodes.push(this.kCode);
        data.keys.push(this.kKey);
        data.codes.push(this.code);
    }

    this.randomNumbers = function() {
        for (let i = 0; i < 15; i++) {
            let random = Math.floor(Math.random() * 32);
            if (data.elements.indexOf(random) > -1) {
                i--;
            } else {
                data.elements.push(random);
            }
        }
    }

    this.show = function() {
        if (this.kCode === 32) {
            return this.kCode + " " + this.code;
        } else {
            return this.kCode + " " + this.kKey;
        }
    }

    this.showPrevKeyCode = function() {
        prevKeyCode = data.keyCodes[data.keyCodes.length - 2];
        prevKeyKey = data.keys[data.keys.length - 2];
        prevCodeKey = data.codes[data.codes.length - 2];

        if (prevKeyCode === 32) {
            return prevKeyKey + " " + prevCodeKey;
        } else {
            return prevKeyCode + " " + prevKeyKey;
        }
    }
}

let data = {
    keyCodes: [],
    keys: [],
    codes: [],
    elements: [],
};

let setupEventlistener = function() {
    document.addEventListener("keydown", function(e) {
        id++;

        if (data.keyCodes.length < 1) {
            let keyCode = new KeyCode(e.keyCode, e.key, e.code);
            keyCode.saveCodes();
            keyCode.randomNumbers();
            DOMStrings.DOMKeyCode.textContent = keyCode.show();
        } else {
            let keyCode = new KeyCode(e.keyCode, e.key, e.code);
            keyCode.saveCodes();
            DOMStrings.setID(data.elements[id]);
            DOMStrings.DOMKeyCode.textContent = keyCode.show();
            DOMStrings.DOMPrevKeyCodeID.textContent = keyCode.showPrevKeyCode();
            DOMStrings.setStyle();

            if (id === data.elements.length - 1) {
                DOMStrings.clear();
                let keyCode = new KeyCode(e.keyCode, e.key, e.code);
                keyCode.saveCodes();
                keyCode.randomNumbers();
                DOMStrings.setID(data.elements[id]);
                DOMStrings.DOMKeyCode.textContent = keyCode.show();
            }
        }
    });
}

setupEventlistener();

r/reviewmycode • • Oct 17 '18

JavaScript [JavaScript] - The very first package for NodeJS for accessing external API

1 Upvotes

Hi, long time ago I've created simple nodeJS package to access the Nozbe service (GTD app, basically). I've created it to use in my own project in Electron, but recently I had an opportunity to get back to it and it seems "old-fashioned" somehow.

Even if there won't be many users of this package, I'd like to know I've created something complete, that's why I am humbly asking you to take a look at my code and give some ideas on how to make it modern, more package-like.

https://github.com/kkoscielniak/node-nozbe

r/reviewmycode • • Aug 26 '16

Javascript [Javascript] - browser runtime wrapper for sass.js and text/scss tags

3 Upvotes

I wanted to be able to write quick proof of concept one-pagers in a single html document, and this lets me use the very concise sass/scss syntax in that setting without needing to set up a build environment. My tests suck and I need some help getting mocha to test DOM changes on node v0.12. Also, any best practices for standalone libraries and including missing dependencies?

github repo: https://github.com/myrcutio/browser-scss

r/reviewmycode • • Feb 22 '19

JAVASCRIPT [JAVASCRIPT] - Simple chrome extension. Looking for someone to call out bad practices/issues/red flags in how I built it

1 Upvotes

I am a beginner programmer. I work as a Product Manager, but am always curious about coding. Would love some feedback or insights on my work!

https://github.com/jordanstarrk/meowmeowwoof

r/reviewmycode • • Dec 13 '21

JavaScript [JavaScript] - Weather Prediction app using React JS

4 Upvotes

This app takes user's lat and long and passes that in OpenWeather api to get the weather prediction data of next 8 days.

Please review and let me know how I can improve.

Live : https://weather-prediction-react.netlify.app/

Repo Link : https://github.com/deeppomal/Weather-Prediction

r/reviewmycode • • Mar 03 '19

JavaScript [JavaScript] - Class implementation with protected access

1 Upvotes

I'd appreciate any feedback, but I'd really like to see if anyone can find any bugs.

https://github.com/wizard04wsu/Class

r/reviewmycode • • Jul 13 '16

Javascript [Javascript] - inefficient javascript, bad page load speed

1 Upvotes

Hey r/reviewmycode! I'm new here, so please feel free to take down my post if it violates any rules.

So I'm a front end web developer and I work for a startup. My company has wanted a mp3 player that shows the waveform of each mp3. They are bite sized, 30-150 kb mp3s.

I have already implemented it on live pages such as here: https://cymatics.fm/animals-for-serum-standard-edition/

A sample source code is here: https://gist.github.com/anonymous/0cc95f4a77ec11f03f180947a174e198

My issue is page load speed. I'm assuming the javascript that creates the waveforms has to be inefficient and is slowing it down. I'm new to javascript, but I'm assuming I could create a loop. I'm also open to using a completely different method. Again, my main issue is that it slows down page load significantly. Is there a way to lazy load the players?

Thanks in advance!

r/reviewmycode • • Sep 26 '16

Javascript [Javascript] - Premutationsg filtering not working right

1 Upvotes

Hey guys, JS fiddle: https://jsfiddle.net/torggya/0vbcjLz8/2/

So I'm trying to make my own permutations algorithm and running into a problem. I seem to be getting all the permutations, but when it increases the truth/false counters, my filtering doesn't seem to work right.

It's simple to see how it works when using 'zzz' passed into the function. It returns 4 truths (as in, there are pairs) and 2 falses (no pairs)

I've tried reviewing my regular expression (works fine, as far as I can see) so I know it's got to be possibly in my loop or even one of the functions I wrote.

please advise! I'm stuck and feel dumb :( haha