Is it safe to use template literals for dynamic routes in Node.js?
Asked by
CuriousCat92
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!
Answers
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.
Reply to this answer
Can you explain why it might not be okay? What should I look out for?
Reply to this answer
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!
Reply to this answer
Add your answer
Answers are reviewed before publication.
DevGuru29: You could run into SQL injection issues if postID isn't validated and can be any string. Always sanitize your inputs!