@nasriya/hypercloud
v1.2.2
Published
Nasriya HyperCloud is a lightweight Node.js HTTP2 framework.
Downloads
307
Keywords
Readme
Visit us at www.nasriya.net.
Nasriya HyperCloud is a lightweight Node.js HTTP2 framework.
Made with ❤️ in Palestine 🇵🇸
Overview
HyperCloud is a robust server-side rendering (SSR) framework designed to build and define components and pages efficiently. The framework supports multilingual pages, handles component rendering, and manages assets seamlessly, ensuring a smooth development experience.
[!IMPORTANT]
🌟 Support Our Open-Source Development! 🌟 We need your support to keep our projects going! If you find our work valuable, please consider contributing. Your support helps us continue to develop and maintain these tools.
Every contribution, big or small, makes a difference. Thank you for your generosity and support!
Key Features
- HTTP2 Framework.
- Component-Based Architecture: Define and build reusable components and pages with ease.
- Multilingual Support: Define localized content for your pages using locals for each language. The framework ensures the correct content is rendered based on the user's language preference.
- Automatic Asset Management: Automatically include stylesheets, scripts, and meta tags from components and global settings in the rendered pages.
- Preserved Asset Order: Maintain the order of assets as defined, ensuring predictable rendering.
- Secure Server with FREE SSL certificates.
- Built-In & Custom Error Pages.
- Built-in (In-Memory) Rate Limiter.
- Built-in Helmet Protection.
Additional Features
- File Upload Handling: Manage file uploads with built-in support for configuring file size limits, handling different file types, and automatically cleaning up temporary files.
- Works well with proxies.
Status
If you encounter an issue or a bug, please open an issue.
Quick Start Guide
Quickly run a HyperCloud
server in 5 easy steps.
1. Installation
npm i @nasriya/hypercloud
2. Importing
Importing in ESM modules
import hypercloud from '@nasriya/hypercloud';
Importing in CommonJS modules
const hypercloud = require('@nasriya/hypercloud').default;
3. Creating & Initializing a server
// Create a new server
const server = hypercloud.Server();
// (Optional) Set the main server so you can use it anywhere
hypercloud.server = server;
:: Advanced Server Configurations ::
4. Defining routes
For now, you only have a server that serves a 404
page on any path, so let's define more routes now using the server's Router
.
const router = server.Router();
// Define a route for the homepage
router.use('/', (request, response, next) => {
response.status(200).send({ data: '<h1>Hello, WOrld!</h1>' })
})
:: Advanced Router Implementations ::
5. Start listening
To start listening for requests just call the listen
method on the server.
server.listen(); // Prints ⇨ HyperCloud Server is listening on port #80
// OR
server.listen(5000); // Prints ⇨ HyperCloud Server is listening on port #5000
For secure servers
server.listen(); // Prints ⇨ HyperCloud Server is listening securely on port #443
// OR
server.listen(8443); // Prints ⇨ HyperCloud Server is listening securely on port #8443
Congratulations! Your server is now ready to handle requests.
Features
HyperCloud has more features and advanced configurations.
Enable Debugging
You can enable debugging to get more details about operations and errors.
hypercloud.verbose = true;
Rate Limiter
Protect your websites against abusive usage by setting limits on how much users can access your site or consume your APIs. The rate limiter can help you prevent small DDoS attacks, but it's not meant for that purpose. We recommend using Cloudflare to protect your resources from DDoS attacks.
Learn how to setup a Rate Limiter here.
Helmet Protection
In today's digital landscape, security is paramount. HyperCloud's built-in Helmet protection is designed to provide robust security measures, safeguarding your applications from a myriad of common web vulnerabilities. By integrating Helmet, HyperCloud ensures that your applications are shielded against threats such as cross-site scripting (XSS), clickjacking, and other malicious attacks. This advanced protection layer helps developers focus on building features and functionality, knowing that their applications are fortified with industry-leading security practices. With Helmet, HyperCloud takes a proactive approach to web security, offering peace of mind and enabling you to deliver secure, reliable applications to your users.
To enable Helmet protection:
server.helmet(); // This applies all the default configurations
Learn how to customize the Helmet here.
Proxy Servers
If your server is running behind a proxy server, you need to configure the proxy
option of the server before initializing it.
Learn how to setup your server behind a Proxy Server here.
Languages
We understand that some sites are multilingual. With HyperCloud, you can easily build multilingual sites.
Supported Languages
You can set a list of languages that your server supports to properly handle language-related requests, like checking users' preferred language to serve them content in their language.
Here's how to set a list of supported languages on your server:
server.languages.supported = ['en', 'ar', 'de'];
Default Language
If a user doesn't have a preferred language, the browser's language is selected then checked against the server's supported languages, if the browser's language isn't supported, the server's default
language is used to render pages or serve other language-related content.
To set a default language:
server.languages.default = 'ar';
Note: The default
language must be one of the supported languages or an error will be thrown.
HyperCloud Built-In User
HyperCloud provides a built-in HyperCloudUser
on each request
and allows you to populate it using a custom handler, you can then access the user
object from any route via the request
object.
The built-in user
object looks like this:
// request.user
{
id: string,
loggedIn: boolean,
role: 'Admin'|'Member'|'Visitor',
preferences: {
language: string,
locale: string,
currency: string,
colorScheme: 'Dark'|'Light'
}
}
Learn how to populate the request.user
object and work with it here.
Error Handling & Pages
HyperCloud provides four built-in error pages out of the box, 401
, 403
, 404
, and 500
. You can render these pages from your code and customize them with your own text, or you can set custom handlers to run whenever you needed.
To render error pages, just call them from the pages
module in the response
object.
router.use('*', (request, response, next) => {
// Render the 401 page.
response.pages.unauthorized();
// Render the 403 page.
response.pages.forbidden();
// Render the 404 page.
response.pages.notFound();
// Render the 500 page.
response.pages.serverError();
})
Learn more about Error Handling & Pages here.
Requests Logging
You can add a logger to log incoming requests by setting a logger
handler.
server.handlers.logger((request, response, next) => {
// Use the request to gather information and log them.
next(); // make sure to call next
})
You can also use another logging packages like Logify to help you with logging.
import logify from '@nasriya/logify';
server.handlers.logger(logify.middlewares.hypercloud);
File Upload Handling
The framework includes a robust file upload handling module that supports various file types and sizes. It allows for flexible configuration of file size limits, dynamic directory management, and efficient memory usage through file streaming. This feature is designed to handle multipart form data, automatically manage temporary files, and integrate seamlessly with other server functionalities.
Here's how:
router.post('/api/v1/uploads', async (request, response, next) => {
try {
// Process the form data and handle the files
await request.processFormData(response);
// Extract fields, files, and the cleanup function from the request body
const { fields, files, cleanup } = request.body as FormDataBody;
// Process the files and fields (e.g., store files, update database)
// ............................
// Clean up temporary files after processing
await cleanup();
// Return a response or proceed to the next middleware/handler
next();
} catch(error) {
response.status(500).json(error);
}
});
Learn more about File Upload Handling here.
Generating eTags
ETags can significantly improve server performance. To generate eTags
for your resources, use the following syntax:
import path from 'path';
hypercloud.generateETags(path.resolve('./src/images'));
The code will generate a unique eTags.json
file in each sub-directory including the provided root
directory.
The generated eTags.json
file will be something like this:
{
"<filename.png>": "<file_eTag>",
"logo.svg": "the-hashed-content"
}
Server Side Rendering (SSR)
You can define multilingual-ready pages by specifying locals for each language. The content of the page changes based on the language.
How it works
Define your pages and components.
Register the pages and components.
// Register pages server.rendering.pages.register('/path/to/your/pages/folder'); // Register components server.rendering.components.register('/path/to/your/components/folder');
Render the pages
router.get('/', (request, response, next) => { response.render('home'); })
Learn how to define components and pages here.
Upcoming Features & Improvements
New features planned for the complete version:
Add a feature to block connections from specific IP addresses or countries to enhance security.
- Implementation Strategy:
- User-Agent Parsing: Use a library to parse the User-Agent string and extract platform details.
- Integration: Integrate this parsing logic into the request handling process.
- Configuration: Allow for enabling/disabling this feature based on user preference.
If you want to request a new feature feel free to reach out:
- Email: [email protected]
- LinkedIn: 🔗 Ahmad Nasriya
License
Please read the license from here.