Implementing RESTful Routing in Node.js
Learn how to effectively create RESTful APIs using routing techniques in Node.js, enhancing usability and clarity.
0 likes
177 views
Rule Content
{
"title": "Implementing RESTful Routing in Node.js",
"description": "Learn how to effectively create RESTful APIs using routing techniques in Node.js, enhancing usability and clarity.",
"category": "Node.js Cursor Rules",
"rules": [
{
"name": "Use Express Router for Modular Routing",
"description": "Utilize `express.Router()` to modularize routes, improving code organization and maintainability.",
"example": {
"code": "const express = require('express');\nconst usersRouter = express.Router();\n\nusersRouter.get('/', (req, res) => {\n res.send('Get all users');\n});\n\nusersRouter.post('/create', (req, res) => {\n res.send('Create a user');\n});\n\nmodule.exports = usersRouter;",
"language": "javascript"
},
"references": [
{
"title": "Best Practices for Organizing Route Handlers in a Node.js Project",
"url": "https://gurubase.io/g/nodejs/best-practices-organizing-route-handlers-nodejs"
}
]
},
{
"name": "Separate Controllers from Routes",
"description": "Keep route definitions and business logic separate by using controllers, enhancing code clarity and reusability.",
"example": {
"code": "// controllers/userController.js\nexports.getAllUsers = (req, res) => {\n res.send('Get all users');\n};\n\nexports.createUser = (req, res) => {\n res.send('Create a user');\n};\n\n// routes/users.js\nconst express = require('express');\nconst userController = require('../controllers/userController');\nconst usersRouter = express.Router();\n\nusersRouter.get('/', userController.getAllUsers);\nusersRouter.post('/create', userController.createUser);\n\nmodule.exports = usersRouter;",
"language": "javascript"
},
"references": [
{
"title": "Best Practices for Organizing Route Handlers in a Node.js Project",
"url": "https://gurubase.io/g/nodejs/best-practices-organizing-route-handlers-nodejs"
}
]
},
{
"name": "Implement Proper HTTP Methods and Status Codes",
"description": "Use appropriate HTTP methods (GET, POST, PUT, DELETE) and status codes to make APIs more understandable and consistent.",
"example": {
"code": "app.get('/users', (req, res) => {\n // Retrieve users from the database\n res.status(200).json(users);\n});\n\napp.post('/users', (req, res) => {\n // Add a new user to the database\n res.status(201).json(newUser);\n});\n\napp.put('/users/:id', (req, res) => {\n // Update user with the given ID\n res.status(200).json(updatedUser);\n});\n\napp.delete('/users/:id', (req, res) => {\n // Delete user with the given ID\n res.status(204).send();\n});",
"language": "javascript"
},
"references": [
{
"title": "What are the best practices for creating RESTful APIs with Node.js?",
"url": "https://reintech.io/blog/best-practices-creating-restful-apis-nodejs"
}
]
},
{
"name": "Validate and Sanitize User Input",
"description": "Use middleware like `express-validator` to validate and sanitize incoming data, preventing security vulnerabilities.",
"example": {
"code": "const { body, validationResult } = require('express-validator');\n\napp.post('/users', [\n body('email').isEmail(),\n body('password').isLength({ min: 8 })\n], (req, res) => {\n const errors = validationResult(req);\n if (!errors.isEmpty()) {\n return res.status(400).json({ errors: errors.array() });\n }\n // Add a new user to the database\n});",
"language": "javascript"
},
"references": [
{
"title": "What are the best practices for creating RESTful APIs with Node.js?",
"url": "https://reintech.io/blog/best-practices-creating-restful-apis-nodejs"
}
]
},
{
"name": "Centralize Error Handling",
"description": "Implement centralized error-handling middleware to manage errors consistently across the application.",
"example": {
"code": "app.use((err, req, res, next) => {\n console.error(err.stack);\n res.status(500).send('Something broke!');\n});",
"language": "javascript"
},
"references": [
{
"title": "Best Practices for Organizing Route Handlers in a Node.js Project",
"url": "https://gurubase.io/g/nodejs/best-practices-organizing-route-handlers-nodejs"
}
]
},
{
"name": "Use Environment Variables for Configuration",
"description": "Store sensitive information like API keys and database URLs in environment variables to enhance security and flexibility.",
"example": {
"code": "require('dotenv').config();\nconst dbUrl = process.env.DB_URL;",
"language": "javascript"
},
"references": [
{
"title": "What are the best practices for creating RESTful APIs with Node.js?",
"url": "https://reintech.io/blog/best-practices-creating-restful-apis-nodejs"
}
]
},
{
"name": "Implement Token-Based Authentication and Authorization",
"description": "Use JSON Web Tokens (JWT) for authentication to ensure that only authorized users have access to certain routes or data.",
"example": {
"code": "const jwt = require('jsonwebtoken');\n\napp.post('/login', (req, res) => {\n // Authenticate user\n const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });\n res.json({ token });\n});\n\nconst authenticateJWT = (req, res, next) => {\n const token = req.header('Authorization');\n if (token) {\n jwt.verify(token, process.env.JWT_SECRET, (err, user) => {\n if (err) {\n return res.sendStatus(403);\n }\n req.user = user;\n next();\n });\n } else {\n res.sendStatus(401);\n }\n};",
"language": "javascript"
},
"references": [
{
"title": "Creating RESTful APIs with Express.js: Tips and Best Practices for Full Stack Developers",
"url": "https://www.flexnoon.com/creating-restful-apis-with-express-js-tips-and-best-practices-for-full-stack-developers/"
}
]
},
{
"name": "Enable CORS for Cross-Origin Resource Sharing",
"description": "Configure CORS to allow or restrict cross-origin requests, ensuring secure and controlled access to your API.",
"example": {
"code": "const cors = require('cors');\n\napp.use(cors({\n origin: 'https://example.com',\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization']\n}));",
"language": "javascript"
},
"references": [
{
"title": "Creating RESTful APIs with Express.js: Tips and Best Practices for Full Stack Developers",
"url": "https://www.flexnoon.com/creating-restful-apis-with-express-js-tips-and-best-practices-for-full-stack-developers/"
}
]
},
{
"name": "Document Your API",
"description": "Use tools like Swagger or Postman to create interactive documentation, providing details on each endpoint, request parameters, and response formats.",
"example": {
"code": "const swaggerJsDoc = require('swagger-jsdoc');\nconst swaggerUi = require('swagger-ui-express');\n\nconst swaggerOptions = {\n swaggerDefinition: {\n openapi: '3.0.0',\n info: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'API Information',\n },\n servers: [\n {\n url: 'http://localhost:3000/api',\n },\n ],\n },\n apis: ['./routes/*.js'],\n};\n\nconst swaggerDocs = swaggerJsDoc(swaggerOptions);\napp.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));",
"language": "javascript"
},
"references": [
{
"title": "Common Pitfalls When Building RESTful APIs with Node.js",
"url": "https://infinitejs.com/posts/common-pitfalls-restful-apis-nodejs/"
}
]
}
]
}