Is it safe to use template literals for dynamic routes in Node.js?

0
4
Asked By CuriousCat92 On

Hey everyone! I'm trying to figure out if it's safe to use template literals for dynamic routes in a Node.js application. For example, I have this Express route:

app.get("/posts/:postID", (req, res) => {
//retrieve post info from database
});

And then on the frontend, I have this function to get the post information:

async function getPostInfo() {
const response = await fetch(`/posts/${postID}`);
const post = await response.json();
return post;
}

If I ensure that I'm using parameterization for my PostgreSQL queries, is this a reliable approach? I'd love to hear your thoughts, especially since I'm new to Node.js and want to avoid potential XSS or other vulnerabilities. Thanks for any advice!

3 Answers

Answered By CodeWizard77 On

Using template literals in front-end requests is generally fine, but remember that anyone can request any post ID since there's no authentication check on what's valid. Just make sure your backend is secure and you're properly parameterizing your SQL queries to protect against any injection attacks. Don't forget to enforce some logic on valid post IDs!

CuriousCat92 -

That makes total sense, thanks a lot for clarifying!

Answered By QuestioningDev On

Can you explain why it might not be okay? What should I look out for?

DevGuru29 -

You could run into SQL injection issues if postID isn't validated and can be any string. Always sanitize your inputs!

Answered By DevGuru29 On

It's a safe approach as long as you know the postID should only be an integer. Things get tricky if it can be a string—just avoid building SQL queries by concatenating strings. Use a library or ORM that supports parameterized queries to fend off any security risks.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.