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
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!
Can you explain why it might not be okay? What should I look out for?
You could run into SQL injection issues if postID isn't validated and can be any string. Always sanitize your inputs!
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.
That makes total sense, thanks a lot for clarifying!