r/node • • Oct 23 '23

Roast my server.ts code of express and what to improve

Post image

Roast my server.ts code of express and what to improve

359 Upvotes

240 comments sorted by

255

u/ichdochnet Oct 23 '23

You are serving your server side code and quite possibly your configuration and secrets with „express.static(__dirname)“.

64

u/EvilPencil Oct 23 '23

I get all kinds of requests for /.env on my production server. Probably at least 3 per day. Need to get that WAF going...

38

u/connormcwood Oct 23 '23

If you’re not serving your whole directory like OP is doing don’t worry about it too much. Serving a public folder only and assuming you’re happy with what’s in the public folder you don’t need to

Then again, I’d advise against serving assets from node. Just set up Cloudfront and S3 and serve from there

38

u/im_a_jib Oct 23 '23

Just

18

u/IHaveFoundTheThings Oct 23 '23

Thank you for this comment!

As devs we always say stuff like that… and then we’re 3 days later still in a rabbit hole while finally realising that we wasted so much time for little to no gain

8

u/antrax-kd Oct 23 '23

This 👌

7

u/[deleted] Oct 24 '23

Thank you for this comment!

As Redditors we always want to say stuff like that… but can quite find the right words. Thankfully, others are great wordsmiths and are capable of phrasing it exactly how we had it in the deep corners of our brains.

1

u/4esv Oct 27 '23

Thank you for this comment!

As silly geese we always want to say stuff like that... But wee find ourselves wanting to continue a joke but can't quite follow the format and get a proper continuation. Thankfully others know how to mimic structures well enough to get a good laugh out of the unintentional setup

13

u/[deleted] Oct 23 '23

It’s not really difficult if that’s what you’re getting at, I have to set up new S3/cloudfront distributions at work all the time

11

u/im_a_jib Oct 23 '23

Not difficult for you because you do it all the time

11

u/[deleted] Oct 23 '23

Nah, it’s really not that difficult in the first place. I taught myself how to do it at my current job and I had no AWS experience before. If I can do it, I promise anyone can

3

u/[deleted] Oct 24 '23
→ More replies (2)

1

u/_ohmu_ Oct 24 '23

I think the point is to not optimize too early

1

u/[deleted] Oct 24 '23

Do whatever you think is best, there are no wrong answers

3

u/connormcwood Oct 23 '23

This should teach you how to do it, you change the assets to whatever you want. Static NextJs is an example

Deploy your static application to AWS Cloudfront using CDK (with S3) https://youtu.be/4nbVvyoeXB8

2

u/_colemurray Oct 24 '23 edited Oct 31 '23

I made an open-source AWS CDK stack that will deploy the s3 bucket and cloudfront distribution pre-configured.

Code: https://github.com/devkit-io/s3-cloudfront-assets-cdk/tree/main

You can deploy it with one click here: https://dev-kit.io/templates/s3-cloudfront-assets-hosting

0

u/[deleted] Nov 16 '23

Just

Come on, its not like setting up a simple S3 + Cloudfront can't be done in under 10 minutes.

The slowest part is the actual bucket refreshing policies and it takes like 60 seconds at most.

Yall' complain too much

4

u/polyocto Oct 23 '23

It’s fine for dev, but I agree that beyond that at the very least have something like Nginx take care of it.

1

u/polandtown Oct 24 '23

noob who lurks here.

this is for security (don't private info in a public dir) and also to prevent nefarious acts? (hey, let's dump a ton of shit into this public dir and fill thier HD)???

1

u/grantrules Oct 24 '23

Yeah exposing __dirname just gives people access to your app's code and possibly app secrets like API keys or SQL credentials which you generally don't want known. Generally it won't allow them to upload files to the server, but if they can find a way to exploit they code they found to allow it, it could happen. At the very least you want to specify a specific directory like __dirname + "/static" so only the files you put in the "static" dir are served.

1

u/polandtown Oct 24 '23

thank you :)

bit by bit i'm learning, from kind folks like you.

1

u/HackTVst Oct 24 '23

Yeah, just. The OP is probably just running a dev server for educational purposes. But even in production, it's like telling someone to not use the VPS disk they already have and go ahead to pay for S3 coz it's "recommended"

0

u/slimenetwork Oct 23 '23

If you are actually getting a lot of traffic to your public assets and you have large files like uncompressed PNGs or audio files then S3 can become very expensive. I have been using bunny.net and it is considerably cheaper ($1 / month minimum with about 1/5th the cost of AWS calculating data transfer out)

21

u/gomihako_ Oct 23 '23

This is the only good code review here the other comments are nitpicky bullshit

11

u/polyocto Oct 23 '23 edited Oct 24 '23

Yup. Creating a folder called ‘public’ or ‘static’, and then serving that would be a better approach I think?

3

u/User31441 Oct 24 '23

Either that or hiding node behind a reverse proxy like Nginx and using that to serve static files instead

1

u/ken_addams_ Oct 23 '23

Isn't __dirname unavailable in modules.

1

u/No_Cartographer_6577 Nov 04 '23

nah

1

u/No_Cartographer_6577 Nov 04 '23

__dirname unavailable in browser

1

u/ReelTooReal Oct 26 '23

The indentation issue is obviously more critical

50

u/buffer_flush Oct 23 '23 edited Oct 23 '23

I’d use a route group for /api it’d make things easier to apply middlewares specific to API related routes.

express.static(__dirname) scares me a bit as you’d need to be pretty careful not to put anything secret on that path or it’d be exposed publicly.

-3

u/[deleted] Oct 24 '23

It looks like it is for school so exposing the server source was done probably so he can be graded.

And even if it isn’t, I think you should always give opportunities to make money to the smart students while they are attending high school, so I’d still approve it cause worst case scenario you effectively stimulate the school economy.

The benefits are numerous.

The stupid drug dealers pay their hacker classmate to change their grades and now they have good enough grades to go to college. The fat kid has to spend his lunch money on buying a grade change and loses weight. The small business type students selling candy or walking dogs or washing cars now have a very practical thing to spend their money on, instead of brain rotting video games. The other nerdy students now have a god to worship, and if he’s REALLY smart he’ll implement a tithing system along with moral guidelines. Etc etc

All it takes is to get the money flowing and all of a sudden you’ve influenced the lives of the entire student body.

All with one line of bad code

1

u/Mammoth_Marsupial622 Oct 25 '23

you are acting like compromising a whole school’s academic integrity is no big deal. yeah this is a great movie plot but people compete for scholarships and real money based off grades. they must follow the CIA triad

86

u/vainstar23 Oct 23 '23

*IQ distribution meme

Left side: Looks ok, merge to main

Center: Nooooo!!! You have to add authentication! Helmet!! Yon can't just use DEFAULT IMPORTS!!

Right side: Looks ok, merge to main

31

u/[deleted] Oct 23 '23

3 YOE Engineer: "I read on a blog that best practices for <x> state that...."

10 YOE Engineer: "I can read it. I know what its doing. Code isn't atrocious. SHIP IT."

-8

u/lifeofhobbies Oct 23 '23

Nothing to do with YOE. It's a developer who is aware of the business value of their contributions vs a developer who doesn't.

10

u/MatthewMob Oct 23 '23

And that awareness typically comes from YOE in a real business environment.

-3

u/lifeofhobbies Oct 23 '23

Not really, it's more about the individual's ability to learn. If one needs 10 years to understand how their company makes profit and how their contribution relates to that, one is slow at learning. People who are good at learning, they know those info even before working in a company.

1

u/MatthewMob Oct 23 '23 edited Oct 23 '23

Sure, maybe not years, but for most I would say it is necessary to have some amount of actual work experience before they are able to see past their own nose in relation to where a developer and their code actually fit in to how a project is completed in the real world.

When learning most (are made to) only focus on themselves and what they are doing - code quality, best practices and using the latest tech. In a real world environment you have real deadlines, real requirements and real people to answer to that force you to compromise and realize that your technology and code is just a means to an end for a business goal.

I'd say most people aren't born with that and also aren't adequately taught it in bootcamps, university or online courses.

1

u/lifeofhobbies Oct 23 '23

Yeah so it's about how an individual learns in such environment, and not much about the number of years of being in that environment. The main point is still about the individual, not how long the time is spent.

6

u/[deleted] Oct 23 '23

itsajoke.jpg

0

u/[deleted] Oct 23 '23

[deleted]

1

u/vainstar23 Oct 24 '23

I've worked for companies that called it "base" or "production"..

This one time during the period during the BLM movement when companies were renaming master to main, GitHub was still configured to use master as the default branch so we basically had to ignore it until we could switch the default branch back to main.

There were also some issues because a lot of stuff like CD was configured to follow master. It was quite messy but at least now everything is resolved. I even got used to saying main now instead of master.

23

u/Poppotato Oct 23 '23

lgtm! push it to prod!

1

u/StickyRibbs Oct 27 '23

This is the right answer.

144

u/Acktung Oct 23 '23

No api versioning, no rate-limit, no helmet, no auth, no open-api...

73

u/r0ck0 Oct 23 '23

No motherfucking Hootie & The Blowfish

3

u/[deleted] Oct 23 '23

I remember your crazy remarks...

3

u/IanMacDooglas Oct 23 '23

Don't think I've EVER seen a Soulfly reference on Reddit, thanks for the throwback

2

u/r0ck0 Oct 24 '23

Surprised I got this many upvotes, haha.

Not sure how many knew it from Soulfly, or just found it funny otherwise or something?

6

u/xxxdarrenxxx Oct 23 '23

I mean technically you can even add 20 more things to make any part better.

OP's question is so un-pragmatic without a context. The smart answer is if u need a base set of these features from the start, just start with a full framework like nest.js or laravel or django and not even bias towards a language for true architectural decision making and/or robustness

2

u/last-cupcake-is-mine Oct 25 '23

All things to configure on the api gateway instead

3

u/[deleted] Oct 23 '23

Won't helmet clash with cors?

2

u/[deleted] Oct 23 '23

What do you mean by open-api?

12

u/[deleted] Oct 23 '23 edited Oct 23 '23

OpenAPI is a spec for typing and documenting your endpoints. You can use tooling that implements the OpenAPI spec to generate types, clients, and servers in multiple languages.

Imagine you had 100+ endpoints and you needed to delve into code to know what HTTP codes they returned, their types, their params, etc.

5

u/rotten_911 Oct 23 '23

I AM on this page and my sanity is 3 meters from me

1

u/[deleted] Oct 23 '23

Sending positive engineer vibes to you

4

u/karborised Oct 23 '23

Basically a swagger spec

1

u/ChinoSenpai Oct 23 '23

How to add a rate limit in this case?

-2

u/Bright_Bonus9823 Oct 23 '23

Redis bro

3

u/PrestigiousZombie531 Oct 24 '23

add rate limiters to nginx, keep rate limiting logic outside express and node

2

u/[deleted] Oct 23 '23

Please explain more

→ More replies (3)

1

u/Careful_Whole2294 Oct 23 '23

Im new to node, what is helmet (a helmet)? Is that a node thing? Or a broader concept?

1

u/[deleted] Oct 26 '23

Have to scroll down a bit but it’s essentially to protect against the most common server vulnerabilities so your stuff is secure. Hints a helmet for your server 🪖

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/deployment

0

u/fordon_greeman_ Oct 23 '23

had to look it up myself. when in doubt, search it up on NPM's website:

https://www.npmjs.com/package/helmet

1

u/[deleted] Oct 26 '23

Hey… you’re a helmet

29

u/[deleted] Oct 23 '23

Why oh why is there a tab there.

7

u/r0ck0 Oct 23 '23

Might have got thirsty, and ordered a tab?

2

u/cjthomp Oct 23 '23

If you want a Pepsi, pal, you gotta pay for it!

0

u/Xerxys Oct 23 '23

Is coke ok? Gets out baggie with whitish powder …

12

u/[deleted] Oct 23 '23

I thought it looked nice.

95

u/xroalx Oct 23 '23
  • Do not split imports.

  • Do not use default exports.

  • Redundant type declaration for app.

  • Unnecessary comments (middlewares, all routes, ...).

  • Unnecessary indentation (app.use(express.json())).

  • express.json() and bodyParser.json()? Why?

  • Endpoints are typically pluralized in REST. users, students, questions...

  • Unclear naming. What's connect from utils/connection?

Not much else to say about this, there's not a lot happening just here.

45

u/Cyberphoenix90 Oct 23 '23

Surprised someone agrees with my "don't use default exports" preference. Default exports only lead to issues and give no benefit in my opinion. Can't even auto import them because the thing you want to import has no name

13

u/xroalx Oct 23 '23

Oh don't worry, there're more of us.

3

u/Lumpenstein Oct 23 '23

One of us!

4

u/[deleted] Oct 23 '23

There’s literally dozens of us!

1

u/yolocat_dev Oct 23 '23

happy cake day!

1

u/mirajehossain Oct 23 '23

one of us 🙂

11

u/edaroni Oct 23 '23

Default exports are so 2021, named exports is all the hype these days.

2

u/EvilPencil Oct 23 '23

100% this. Default exports are hot garbage, why the eff are they in the Airbnb eslint rules?

12

u/Chronox Oct 23 '23

Split imports, but not like that. Split third party libraries apart.

-7

u/xroalx Oct 23 '23

I don't see a reason to do that.

12

u/Chronox Oct 23 '23

What's the reason to do any stylizing, then? Just cleaner to group similar and separate the groups with a space.

-3

u/xroalx Oct 23 '23

Most of the time, your imports are automatically inserted by the editor and you generally skip imports when reading code, so manually managing them and moving them around just sounds like a lot of manual work that might end up being inconsistent anyway and the imports end up taking more vertical space.

If you have it automated via an editor/prettier plugin, I still find it unnecessary but it's fine. That doesn't seem to be the case here, though, because of the manual comment.

→ More replies (1)

4

u/rkd6789 Oct 23 '23

Can you explain, do not split imports

-2

u/xroalx Oct 23 '23

Grouping import statements and separating them with empty lines.

VSCode already sorts the imports quite sensibly, it auto-imports stuff you reference, there's no added benefit in manually managing which import goes where and moving them around.

If you have a prettier plugin to do it, fine, but I don't really see the point anyways.

1

u/rkd6789 Oct 23 '23

I see. Thanks for explaining

1

u/Anbaraen Oct 24 '23

I have not found VSCode to automatically sort imports sensibly, FWIW.

3

u/RubbelDieKatz94 Oct 23 '23

All of this formatting stuff can be easily standardized by adding a husky hook on commit with pretty-quick.

1

u/Tjq866 Oct 23 '23

Would you say that his routes could be imported from an index.js from routes?(one liner)?

8

u/xroalx Oct 23 '23

Unless the code gets too long to have it all in one place, I actually prefer the approach OP chose.

If the code got too long, I'd probably create a routes/routes.ts file and put the route setup there.

Either way, neither one is inherently good or bad in my opinion.

What I do consider bad though is using the index name and relying on the resolution algorithm, as that is not part of the JavaScript standard, it's just something Node supports, and I believe it doesn't even work if you're running Node in ESM mode.

2

u/[deleted] Oct 23 '23

Use a single file until it grows "large enough" to split it up into distinct modules. Keep them all in the same folder and don't try to abstract too early, even if you think it'll make sense later to do so.

One thing I've learned as an engineer is that your file architecture should be as simple as possible in the beginning and not to fuck with it until you actually need it be more complex.

My biggest mistakes as a new engineer was 1) using index files out of the gate and 2) splitting and colocating type files.

I learned a very important lesson at 4PM one day about circular imports.

1

u/Tjq866 Oct 23 '23

A few projects ago I think I started to over abstract. I was making helper functions to handle dispatches in the front end, I think with all the advice I heard about keeping things modular I just went overboard, but sometimes it is hard not to. I like your advice about keeping things simple at first.

2

u/[deleted] Oct 23 '23

I would also advise to keep meta-work distinct from feature-work.

Ship the feature first using whatever is in place. Then, if you have to reorg, cut a different commit for that. This way you can keep your changes separate and you don't have to roll back a feature for some borked internal bug.

1

u/Tjq866 Oct 23 '23

Thanks. I never considered that. The bootcamp I went to used an index file and just exported the router from that from a routes/index.js. They also used babel (to allow esm), which is not even recommended for production.

1

u/Anchorman_1970 Oct 23 '23

Why not expressjson snd bodyparder at the time? What if be passes verfiy funxrion. But did not want all body to be verified, only for webhooks

1

u/xroalx Oct 23 '23

Because they both do the same thing.

I'm not sure what verify function you're talking about, what does it have to do with webhooks, or where you see any of that in this code.

0

u/Anchorman_1970 Oct 23 '23

Generally… verify(res, rea, buf)

2

u/xroalx Oct 23 '23

How does that justify using both or how is it even related?

0

u/[deleted] Oct 23 '23

[deleted]

1

u/xroalx Oct 23 '23

Check the other responses.

23

u/[deleted] Oct 23 '23

[removed] — view removed comment

57

u/xroalx Oct 23 '23

A default export inherently has no name, it doesn't tell you what it is, and it's up to the importer to give it a name.

It can be imported as Foo in one file, and as Bar in the other, or foo, or fooh, or anything else. This makes the code inconsistent or it forces you to refer back to previous imports to know what it was called.

Furthermore, if the import name does not match the file name, tooling might not even be able to autocomplete the import, whereas when you try to import something named usersRouter, the editor can look for named exports that match the name.

Let's put it the other way around, default exports have downsides and no benefits over named exports. Why use them in the first place?

There's one valid case - when the file is to be consumed by a tool - such as configuration files. They'd either have to enforce a name, or just roll with default and not care, but such a file is never imported in your own code.

16

u/MrNutty Oct 23 '23

I don’t think default imports are bad. Here are the reasons why

  • forces one not to pollute a file. When used, makes the purpose of the function and file clear. I always export a default named variable that also matches the file name though. Resolves any auto import issues.

  • less chance someone does “import * as Foo”. This pattern I’ve found lead to tools such as ts-prune not pruning a function that’s really unused.

  • less curly braces

Obv all are nit picky but wanted to highlight a positive view. Doesn’t mean Im saying one or the other way is better

5

u/Bullroarer_Took Oct 23 '23

yeah its really a matter of opinion that has been asserted as a law

4

u/MrNutty Oct 23 '23

Yea all of these discussions are usually a matter of opinion using our experience to best create some guidelines.

1

u/Chazgatian Oct 24 '23

You crazy.

0

u/[deleted] Oct 23 '23

[deleted]

2

u/MrNutty Oct 23 '23

🤣 semi colons are also useless

1

u/lifeofhobbies Oct 23 '23

Default export is fine as long as you have a naming convention, like in everything else.

3

u/Chazgatian Oct 24 '23

See the reasoning in all other threads. This is terrible advice

0

u/lifeofhobbies Oct 24 '23 edited Oct 24 '23

Terrible only for you maybe.

Function exported is named foo, file name is named foo, why the hell would anyone importing it name the variable something else. If you do, that's not a default export problem.

2

u/tarwn Oct 24 '23

Now your team decides to rename it to legacyFoo to differentiate it from a new foo that is being built (naming is hard). In the named export version the build (if you're bundling, transpiling, etc) or editor produces errors for any instances you missed and prevents you from continuing until you clean them up. In the default export you missed 2 imports and renamed one of the new imports to legacyFoo without realizing it, and in 3 months some interesting bugs are going to occur when someone makes a change assuming the naming is correct.

1

u/lifeofhobbies Oct 24 '23

It would produce similar errors in the default export version as the code wouldn't run with the import path to a missing file that you renamed. Just like the code wouldn't run with an import variable to a missing named export that you renamed.

1

u/tarwn Oct 25 '23

Sorry, I should have been clearer with "rename it to legacyFoo". Your example fits in that description but isn't what I was trying to describe. If you've never worked on a codebase where the thing being default exported had one name in the file and a variety of different names throughout the codebase, then I'm happy for you. You're correct that if the filename is changed it would cause an error if the import path is not updated too, but there are cases where the filename is already unique enough and not changed, where folks change the filename and the editor automatically updates the path/filename portion of all their imports leaving the and the old module name isn't touched, where folks add local index files to re-export it modules and the names morph along the way, and probably more cases I'm not remembering.

The point is that named exports get extra guardrails that can be automatically updated or throw build errors immediately while you're still making the initial change, whereas default exports do not and in many cases will never give you the extra nudge that there's 3 places still using the old flavor of the name.

→ More replies (5)

1

u/Chazgatian Oct 24 '23

Because they can, and I've seen it happen. That's why it's called an anti pattern

1

u/lifeofhobbies Oct 24 '23

Who called it an anti pattern tho? Why is it the default pattern with React components If thats an antipattern?

6

u/bmcle071 Oct 23 '23

I don’t like them because they aren’t refactorable. If you do a rename then the modules that import the thing you are renaming continue to use the name defined in their import statement.

0

u/[deleted] Oct 23 '23

[deleted]

1

u/bmcle071 Oct 23 '23

What if you want to change the name of the thing? It’s goona happen eventually.

0

u/[deleted] Oct 24 '23

[deleted]

1

u/bmcle071 Oct 24 '23

That’s just the thing, they don’t for default exports. Well at least VSCode doesn’t.

8

u/bongobret Oct 23 '23

Wrote servers like this for years but then I saw the light and switched to fastify. It has built in json schema validation at the framework layer since it’s so important not to screw that part up when processing untrusted user input. Guessing you are hand rolling your validation as one tends to do with express. It’s probably not too late to switch and stop shipping unvalidated api endpoints!

2

u/ArnUpNorth Oct 23 '23

A good programmer will write good code no matter the framework. If OP switches to fastify he ll just lose time refactoring without learning anything useful.

3

u/bongobret Oct 23 '23

You are right, you can write reliable services with express, or even learn a lot rolling your own http handler in node. Refactoring a project from express to node, however, there is still a lot to learn, especially on the validation front. The former approaches tend to neglect this extremely important layer in any http endpoint. It's also just an incredible tool to have some experience on, and its a great way to learn tricks and patterns from some of the top people in the node ecosystem.

1

u/ArnUpNorth Oct 24 '23

Ok but you dont need fastify or any other framework to learn that. When learning to code it s a bit aggravating when someone tells you « use another framework » but you didn t learn why and what was wrong in what you were doing previously. Also if i am not mistaken by default fastify doesn t validate anything neither…

so between adding a lib to do it in express or configuring it in fastify there s not much gain.

2

u/HackTVst Oct 24 '23

Express itself has performance bottlenecks that are identified and solved in Fastify. Express is an inefficient framework if you want to maximize your server performance. But that may not matter to simple apps with less traffic.

2

u/bongobret Oct 24 '23

I totally understand. One asks a general question: I took approach x, did I make any errors? And a common response is “use some other tool du jour” by someone who’s barely used either tool. Annoying pattern, easy to spot.

I want to clarify that the advice here is: if you are writing api endpoints, you are accepting untrusted user input. It’s irresponsible to ship anything but toy examples that lack strong request validation. From a security perspective and a maintainability perspective.

Im suggesting in the first comment and in this comment that fastify is the best path available in the node ecosystem at the moment to learn about robust endpoint validation. It’s a great example and implementation of pretty much everything you should be doing when handling http requests in node. The fact that it also adds a significant performance boost and endpoint documentation as a side effect of the validation specification only drives the lesson home when you learn about this approach. Fastify includes built in validation, it’s not a plugin. These things can be added to express as plugins however having worked in the express ecosystem for years, witnessed many newcomers navigate that ecosystem, these concerns are not emphasized or addressed in that plugin ecosystem very effectively.

12

u/[deleted] Oct 23 '23

Redundant comments, redundant Application type, redundant body-parser

1

u/polyocto Oct 23 '23

Depending on your team’s philosophy, that Application type may be wanted, to remove any doubt.

6

u/arsamsarabi Oct 23 '23

How about we start with putting an index file in the routes folder

6

u/InfiniteMonorail Oct 24 '23

The biggest crime is taking a picture of code.

4

u/connnnnor Oct 23 '23

Get a code formatter so all your lines are indented the same

4

u/tswaters Oct 23 '23

Split server from app. App includes the definition, most everything here... Server requires app and calls listen with the long-form const server = http.createServer(app) ... You can add signal handlers for SIGINT/SIGTERM and gracefully close server connections instead of the default process.exit (results in ECONNRESET to connected clients when app is cycling/upgrading)

7

u/NoMoreVillains Oct 23 '23

My only real complaints are the unnecessary comments for self explanatory code. I don't care for the "no default imports" debate. 9.5/10 claps

2

u/HackTVst Oct 24 '23

The OP seems like a beginner. Comments are basically so you can remember what tf you wrote one year later. They are for you, not other devs, coz this is a personal project.

3

u/Confident_Force_944 Oct 23 '23

Curious about the connect(). Is that connection to database? When starting a server, I generally want two things to happen: server is listening on port and connecting to database, if either fail, fail loudly.

1

u/polyocto Oct 23 '23

I missed that. If it is for a database, then I’d certainly want the connection to be done before the server is ready to serve. This because I’d rather any preflight be done before the server is accepting http connections, otherwise you’ll either become returning 500 errors all the time (assuming the server doesn’t crash).

Also, the if it is for the database, then the module should probably be called ‘database’, to avoid confusion as to purpose.

3

u/SpaghettiOnTuesday Oct 23 '23

Using Express consensually

3

u/ajvg94 Oct 24 '23

Some simple improovements are: rate limit, slow down, cors, helmet, swagger docs

If you already use express.json(), there is no need to use bodyParser

You can add this line to stop the server from returning information about it

app.disable('x-powered-by');

Also you can check this project of mine for some examples. I am still improving but maybe it can help you.

3

u/pausm Oct 24 '23

Use a reverse proxy nginx server for one...

3

u/foflexity Oct 24 '23

I use fastify… does express not have an auto load where you define routes by the directory structure and it loads them dynamically?

9

u/MaxUumen Oct 23 '23

What's the point of polishing the front door if the interior might be filled with garbage.

2

u/tech_ai_man Oct 23 '23

You didn't display the line numbers, making it difficult to comment on a line by line basis.

2

u/ArnUpNorth Oct 23 '23

Maybe at least format the code and have it linted before asking for a roast ? 🙈

2

u/VaradGupta Oct 24 '23

Could refine it by use get and post to be more specific.

2

u/Capable-Lecture2001 Oct 25 '23

Man that app.use("/"..... Is dangerous if put before any other app.use

3

u/deepak379mandal Oct 23 '23

OP is like, I need more of your burn.

2

u/turshija Oct 23 '23

Mixing single and double quotes, both in imports and routes. Add eslint and prettier to handle those kind of stuff automatically.

0

u/[deleted] Oct 23 '23

[deleted]

0

u/LdouceT Oct 23 '23

I'd say that's a reasonably anal thing, it's distracting the same way weird variable names are. Take some pride in your work, this kind of stuff is sloppy.

1

u/[deleted] Oct 23 '23

Very good, nice job... first 7 lines.

1

u/comma84 Oct 24 '23

Roast your own. I’m off the clock, and they are asking too much nowadays

1

u/vv1z Oct 24 '23

Express.json and bodyParser.json are redundant

1

u/alwyn974 Oct 24 '23

Maybe try nestjs it's a powerful framework built on top of expressjs, you can even use fastify if you want.

1

u/VehaMeursault Oct 24 '23

Y'all are aware OP is messing with you, right?

1

u/white__cyclosa Oct 24 '23

Show us your routes you coward

1

u/misterjyt Oct 24 '23

try to configure it to automatically auto route based on directory.. like create a route folder or api folder where you set auto routing in it. So that it follows the folder structure.. this way you dont have to edit that file everytime you add a new route.

like this: in your main js/ts file:

const express = require('express');
const app = express();

organize your routes:

- routes/
  - index.js
  - users.js
  - products.js

sample in user.js:

// In users.js
const express = require('express');
const router = express.Router();

// Define routes for users
router.get('/', (req, res) => {
  // Route handling logic
});

module.exports = router;

in your main file or server.js file. load the route files dynamically using a loop and require. This allows you to automatically load all route files within the routes folder.

const fs = require('fs');
const path = require('path');

// Get a list of route files
const routeFiles = fs.readdirSync(path.join(__dirname, 'routes'));

// Load each route dynamically
routeFiles.forEach((file) => {
  const routePath = path.join(__dirname, 'routes', file);
  app.use(require(routePath));
});

and try listening:

const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

this is just a sample, so you can configure it rourself

1

u/HackTVst Oct 24 '23

Ship it, then modify it as your needs dictate down the road. If you listen to so-called best practices you will end up running Docker, Kubernetes, AWS S3, and God knows what other technologies that are simply overkill. Or you might end up on Serverless or Edge runtime, where you have no clue what is going on with your API.

1

u/goodbalance Oct 24 '23

I'd add graceful shutdown and create a function that "assembles" the app so that later you can insert dependencies with less hassle. E.g. ```const create_app = () => ...```

1

u/[deleted] Oct 24 '23

Seeing app.use(express.json()); tabbed in more than the rest of the code makes me really uncomfortable.

1

u/ublec Oct 24 '23

The audacity you have to use multiline comments for single-line text.

1

u/KeyAromatic7101 Oct 24 '23

Graceful shutdown is something already given by express ? If not, it’s a good improvement

1

u/esmagik Oct 24 '23

I DoNt KNoW whAT a HaShMap Is

DiREcToRY IndeXInG Is 4 NeWbS

Your routes could all be exported / imported from the root of ‘routes’. You could also make a hashMap of {‘/path’: importedRoute} and clean up about 20 lines of this.

1

u/Riday2001 Oct 24 '23

app.use(express.static(__dirname)) 💀

1

u/[deleted] Oct 26 '23 edited Nov 19 '23

chief lavish cooperative innocent panicky fade carpenter theory engine attraction this post was mass deleted with www.Redact.dev

1

u/No_Cartographer_6577 Nov 04 '23

Yoooo bro.. See the app.use stuff. Import all that shi form another file. It's just high coupled BS you don't want to transfer in microservices

1

u/adalphuns Nov 19 '23
  1. stop using express

  2. start using Hapi

1

u/TheRealNalaLockspur Nov 20 '23

God I can't stand it with I see es modules on a backend.

If you truly understood how esm works vs requires, you would never do this.

Here come the downvotes from all the "Sr's" that were shipping clerks in 2019, got laid off because of covid, took a bootcamp, and now they've been a software engineer for 20 years...

Other than that... use express.Router, create an index, create an array of all your routes, and then loop through them and use router.use()

ie:

//mergeParams incase you have upstream router parameter's, or you'll lose them.

const router = require('express').Router({ mergeParams: true })

const routes = [
    { path: '/admin', router: require('./admin') },
    { path: '/customers', router: require('./customers') },
    { path: '/domains', router: require('./domains') },
    { path: '/billing', router: require('./billing') },
    { path: '/auth', router: require('./auth') },
]

for (let route of routes) {
    router.use(route.path, route.router)
}

module.exports = router

1

u/NTAK666 Oct 24 '23

move to Nestjs

1

u/_He1senberg Oct 24 '23

you are using express while u should be using nestjs

1

u/DimensionHot9669 Oct 23 '23

Honestly, for what it is, looks just fine. No worries there! :)

1

u/ArnUpNorth Oct 23 '23

Are you serious? How about serving __dirname 😱 doesnt it raise some alerts for you?

1

u/DimensionHot9669 Oct 23 '23

Depends on the setup, if he's not going with an env file, all connection to db/whatevs is in env but not as an actual file it'll be fine. Sure your code base is leaking but if it's just a little personal project nothing of value is lost. It is also highly dependant on where the entry file is placed. If for example it is app/src/index.ts then it's just the source code being served.

It's clearly a student project and what he has done is more than fine for what it is :)

1

u/ArnUpNorth Oct 24 '23

He s using a configuration file which will be leaking. If you don’t review potential security issues on school projects when someone asks for a review when will OP get the opportunity to learn?

1

u/zambizzi Oct 23 '23

It's way too simple and easy to read! Over-engineer something NOW!

0

u/theus-sama Oct 23 '23

I like to make it as a class. Looks better

1

u/ArnUpNorth Oct 23 '23

For you it does 😅

-2

u/Reaver75x Oct 23 '23

Ts is so stupid.

1

u/prophase25 Oct 23 '23

Lol there’s no difference in this case between TypeScript and JavaScript - Application is inferred from the return type of express()

It may not be necessary here but you can’t tell me TypeScript is useless if you use JSDoc. You wouldn’t happen to use JSDoc would you?

1

u/Reaver75x Oct 23 '23

const app = express() is all you need. If I write that the way he did it would give me an error so it’s definitely not normal JS. I’m not sure why imports is even working on the backend side. I’ve always used require.

1

u/prophase25 Oct 23 '23

I am saying that OP didn’t need to write in the Application type annotation because it is inferred (in TypeScript - yes, you cannot type annotate in JS)

You need to add type: module to your package.json to use import

-3

u/Jyuber Oct 23 '23

you are using express , so keeping your api-docs up to date is impossible / hurcelean task ,

but I see that you didn't bother , so it's most likely not production code .

0

u/fibs7000 Oct 23 '23

What i dont get is why nobody uses classes or at least crate functions...

I would encapsulate the whole server in a class with a run method which first calls an initialize method.

Currently its 1. not very easy testable, 2. no possibility for dependency injection, 3. is statically defined, 4. is impossible to modularize.

I know its a pattern in js to do it like that... but I think only cause you can do it does not mean you should... there are some good oop principles that can be applied here.

0

u/LordFrz Oct 28 '23

Ha, idiot! You used, [language you used], instead of the superior, [language I use]. Fool!

-4

u/RubbelDieKatz94 Oct 23 '23

Maybe use a repo to store your code instead of taking screenshots.

Then again, I used to store my XAMPP directory in zipfiles during my apprenticeship, so ehhhh

-11

u/SSYT_Shawn Oct 23 '23

Use different http library than Express

-5

u/lucsoft Oct 23 '23 edited Oct 25 '23

Don’t use express it’s one of the worst libs out there in context of baseline performance

Edit: There are great alternatives that also still get actively maintained. Like here: https://github.com/denosaurs/bench

1

u/[deleted] Oct 23 '23

what would be a good alternative according to you

1

u/D10S_1 Oct 23 '23

Any benchmarks/references that support your argument? Imo otherwise this comment is rather unhelpful