Astrus is a Node.js web framework focused on fast API development. This project is in alpha and it might contain breaking changes in the future, use at your own discretion.
- ability to implement custom req and res functions
- cors implementation
- multipart streaming (currently loads into memory)
- Installation
- Getting Started
- Static Files
- CORS Configuration
- Controllers
- Middlewares
- Routes
- Request Handling
- Server Startup
npm i astrus
Astrus only supports ESM imports:
import astrus, { route, controller, middleware } from 'astrus'
// Create a new Astrus instance
const app = new astrus()
Serve static files from a directory:
app.serveStatic('./public', '/public')
Configure CORS options:
app.corsOptions({
// default options
origin: null, // Allow all origins when null
methods: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: null, // Which headers can be sent from the browser (null === all)
exposedHeaders: null, // Which headers can be accessible by the browser (null === all)
credentials: false, // Allow browser to send cookies to back-end
optionsSuccessStatus: 204, // Success status
maxAge: 0, // How long to cache the preflight response in seconds
})
Create reusable controllers:
const testController = controller((req, res) => {
res.send("hello world")
})
Create middleware functions with parameters:
const testMiddleware = (roles) => middleware((req, res, next) => {
const { role } = req.segments
if (!roles.includes(role)) {
return res.send("UNAUTHORIZED")
}
return next() // You must always use return when returning next or Response objects/functions
})
const middlewareRoute = route('POST', '/middleware', [testMiddleware(['admin', 'mod'])], (req, res) => {
res.send("AUTHORIZED")
})
Create a single route:
const testRoute = route('GET', '/test0', testController)
app.route(testRoute)
Add multiple routes at once:
const testRoutes = [
route('GET', '/test1', testController),
route('GET', '/test2', (req, res) => {
res.send("hello world")
}),
]
app.route(testRoutes) // Accepts arrays
Use route parameters (dynamic segments):
app.route('GET', '/test4/:segment', (req, res) => {
const { segment } = req.segments
res.send(segment)
})
Handle form data including file uploads:
app.route('GET', '/test5', (req, res) => {
const { image } = req.body
res.header('Content-Type', image.mime)
res.send(image.value)
})
Access Node.js native IncomingMessage and ServerResponse objects:
app.route('GET', '/test6', (req, res) => {
res._.setHeader('Content-Type', 'application/json')
res._.write(JSON.stringify({ address: req._.socket.remoteAddress }))
res._.end()
// NOTE: You can access the wrapper from the _ object, which holds the functions
// implemented by Astrus, example:
// res._.wrapper._.wrapper._.wrapper.send('')
// This is expected behavior since both reference each other.
})
Start the server with specified options:
app.start(
'http', // Protocol
8000, // Port
{}, // Options
() => { console.log('server started') } // Callback
)