lightning-pages
v1.5.0
Published
 # LightningPages Documentation
Readme
LightningPages Documentation
Introduction
LightningPages is a Node.js package designed for creating high-speed, optimized landing pages with enhanced features such as automated image processing, CDN integration, and security enhancements. It's ideal for marketing landing pages, rapid web development, and anyone looking to host fast and efficient landing pages for advertising purposes.
Installation
npm install lightning-pagesor using Yarn:
yarn add lightning-pagesImporting LightningPages
import { LightningPages } from 'lightning-pages';Configuration and Setup
Environment Variables
CDN_REGION: The region of your DigitalOcean space.CDN_ACCESS_KEY: Your DigitalOcean access key.CDN_ACCESS_SECRET: Your DigitalOcean access secret.CDN_BUCKET_NAME: The name of your DigitalOcean bucket.CDN_BASE_URL: Optional. Custom CDN base URL if different from the default DigitalOcean format.SGTM_URL: URL for server-side Google Tag Manager.PORT: The port number your server will listen on.NODE_ENV: Set to "development" to enable development mode.
Creating a DigitalOcean CDN
- Sign up for DigitalOcean and create a Space.
- Set up a CDN for the Space and note down the endpoint.
- Generate and store your access keys securely.
Initializing the LightningPages Application
const LPApp = new LightningPages({
script_sources: ['https://www.googletagmanager.com', 'https://connect.facebook.net', "https://script-cdn.example.com"],
img_sources: [
'https://www.facebook.com', // for facebook tracking
'https://images.somecdn.com' // some image cdn example
],
connect_sources: [
'https://analytics.google.com', // google analytics
'https://www.google-analytics.com', // google analytics
"https://some-api-service.example.com" // example api service
],
font_sources: [
'https://fonts.gstatic.com' // for Google Fonts
],
compression: {
threshold: 1024,
brotli: {
params: {
quality: 4
}
}
},
cdn_baseurl: 'https://bucket-name.region.digitaloceanspaces.com',
projectRoot: __dirname, // optional, defaults to process.cwd()
production: false, // set to true for production mode
favicon: 'favicon.ico' // custom favicon filename in the public directory
});Core Features
Image Handling
- Automatically watches the
/public/imagesfolder. - Converts new images to WebP format for optimized loading.
- Synchronizes with DigitalOcean CDN for global distribution.
- Provides methods for manual image conversion and uploading via the
imagesproperty.
Compression and Performance
- Uses
@fastify/compressfor compressing responses. - Supports Brotli compression for enhanced performance.
- Improves loading times and PageSpeed score.
- Configurable compression threshold and quality settings.
Security with Helmet
- Implements
@fastify/helmetfor basic security setups. - Configures Content Security Policy (CSP) directives for scripts, images, connections, and fonts.
- Customizable security directives for different content types.
CSS Cache Buster
- Watches CSS file for changes.
- Updates the global CSS cache on modification.
- Provides a manual cache bust endpoint at
/css/cache/bust.
CDN Integration
- Seamless DigitalOcean Spaces CDN integration.
- Automatic redirect of static files to CDN URLs.
- URL rewriting for image sources to use CDN paths.
- Dedicated
/cdn/*endpoint for direct CDN access.
Server-Side Google Tag Manager
- Proxies requests to Google Tag Manager through the
/s-g-t-m/*endpoint. - Retains headers and request body for accurate tracking.
- Useful for avoiding client-side GTM implementation.
Favicon Support
- Built-in favicon handling through the
fastify-faviconpackage. - Customizable favicon filename.
Creating Custom Endpoints for EJS Templates
Serving a Static EJS Page
LPApp.page('/about', async (req, reply) => {
const data = {
domain: 'Your Domain',
title: 'About Us',
css: LPApp.getPageCSS(),
otherData: 'Additional data if needed'
};
return reply.view('views/about.ejs', data);
});In this example, the /about route serves a static EJS page named about.ejs. We pass an object containing data like domain, title, and CSS, which the EJS template can use.
Dynamic Page Rendering Based on URL Parameters
LPApp.page('/:filename', async (req, reply) => {
// Retrieve filename from the URL parameter
// @ts-expect-error
const filename = `${req.params.filename}.ejs`;
// Additional logic to determine domain and title based on the filename or other criteria
const { domain, title } = someFunctionToDetermineDomainAndTitle(filename);
// Checking if the file exists
const fullFilePath = path.join(LPApp.projectRoot, 'views', filename);
const exists = fs.existsSync(fullFilePath);
if (exists) {
return reply.view(filename, {
domain,
title,
env: process.env,
css: LPApp.getPageCSS()
});
} else {
// Fallback if the requested file does not exist
return reply.code(404).send('Page not found');
}
});Here, the /:filename route dynamically serves EJS files based on the URL parameter. The filename is extracted from the URL and used to render the corresponding EJS file. If the file doesn't exist, it returns a 404 error.
Project Structure
LightningPages expects the following directory structure:
your-project/
├── public/
│ ├── css/
│ │ └── style.css # Main CSS file
│ ├── images/ # Images folder (watched for changes)
│ └── favicon.ico # Optional custom favicon
├── views/
│ └── *.ejs # EJS template files
└── index.js # Your application entry pointAPI Reference
LightningPages Class
The main class for creating and managing your landing pages.
Constructor Options
projectRoot(string, optional): Root directory of your project. Defaults toprocess.cwd().port(number, optional): Port number to listen on. Defaults toprocess.env.PORTor 8000.cdn_baseurl(string, optional): Base URL for your CDN.font_sources(string[], optional): Array of allowed font sources for CSP.script_sources(string[], optional): Array of allowed script sources for CSP.img_sources(string[], optional): Array of allowed image sources for CSP.connect_sources(string[], optional): Array of allowed connection sources for CSP.compression(object, optional): Compression options for @fastify/compress.production(boolean): Whether to run in production mode.favicon(string, optional): Custom favicon filename in the public directory.
Methods
page(url: string, callback: RouteHandlerMethod): Define a custom page route.getPageCSS(): Get the cached CSS content.start(port?: number): Start the server on the specified port.
ImageHandler Class
Handles image processing and CDN uploads.
Methods
updateImageFolder(filepath: string): Process and upload new images.convertToWebP(filePath: string): Convert an image to WebP format.checkAndUploadImages(imageFolder: string): Upload all images in a folder to CDN.
DigitalOceanCDN Class
Manages interactions with DigitalOcean Spaces CDN.
Methods
uploadImage(file: Buffer, fileName: string): Upload an image to the CDN.removeFromBucket(filePath: string): Remove a file from the CDN.
Starting the Server
LPApp.start();Listens on the specified port and starts serving your landing pages.
Frequently Asked Questions
How do I create my own landing page?
Initialize the LightningPages application, configure routes, and start the server.
Can I build a landing page for free?
Yes, with LightningPages and a Node.js environment, you can create landing pages for free.
What app can I use to create a landing page?
Use the LightningPages package in a Node.js environment.
What is the cheapest way to create a landing page?
Hosting a landing page on a Node.js server using LightningPages is very cost-effective.
Can you have a landing page without a website?
Yes, LightningPages allows you to host standalone landing pages.
How much does a landing page cost?
Costs vary based on hosting and CDN usage, but LightningPages itself is free.
How do I make my page speed faster?
Utilize LightningPages' compression, image optimization, and CDN integration.
How to get 100 page speed?
Optimize images, use efficient CSS/JS, and leverage caching and CDN features of LightningPages.
How do I increase my PageSpeed score?
Optimize resource loading, minimize CSS/JS, and use LightningPages' performance features.
How do I reduce page loading time?
Utilize LightningPages' automated image processing, CDN integration, and server-side optimizations.
