uniserv
v0.0.1
Published
Use Server Side Rendering Anywhere.
Downloads
6
Readme
Universal Server Side Rendering (SSR)
Use Server Side Rendering (SSR) everywhere.
Inspired from @sveltech/ssr.
Features
- Typescript support.
- Ease of Integration. You can integrate it with Golang, Rust, Java, PHP and etc via HTTP Server or Child Process.
- Can be used with Vanilla JS, jQuery, Svelte, Routify, Handlebars and etc. (On Progress)
- Can be use in Lambda Server. (NodeJS v10 or newer required.)
- Passing custom Props like
cookie
,session
and etc to Javascript Code.
Installation
We don't need any special template. Just install the uniserv
library with your package manager:
yarn add uniserv
# or
npm i uniserv
Usage
Using Express JS (Node JS)
const express = require('express')
const { readFileSync } = require('fs')
const { renderToString } = require('uniserv')
const template = readFileSync('./public/template.html', 'utf8')
const script = readFileSync('./public/script.js', 'utf8')
const server = express()
// If you are using a JS framework like Svelte, Routify, etc.,
// please uncomment the code below to use Dynamic Import (or Lazy Component)
// server.use(express.static('./public'))
server.use((req, res) => {
renderToString(
template,
script,
{
// Put in here the data you want to access it from Javascript code.
// You can access the data in `window.serverProps`.
// Example:
pageTitle: `Now you're in: ${req.path}`,
},
{
path: req.path,
}
)
.then((stringHtml) => {
res.send(stringHtml)
})
.catch((error) => {
// Handle error in here
})
})
server.listen(3000)
API
renderToString(html, script, serverProps, options)
Description
Render HTML & Javascript code to string.
Arguments
html
- HTML string that will be processed.script
- Javascript code that will be executed.serverProps
- Custom data that will be passed toscript
code. The data can be accessed fromwindow.serverProps
.options
- Configurationhost
- Hostname to use while rendering process. Default:http://jsdom.jss
(You can use anything. But make sure to use the valid Hostname.localhost
is an invalid instance.)path
- Will be used forwindow.location.pathname
.eventName
- If exists, the output HTML string will be returned after event emitted. If not, it will be returned immediately.userAgent
-userAgent
affects the value read fromnavigator.userAgent
, as well as the User-Agent header sent while fetching sub-resources.cookie
- Will be used fordocument.cookie
.beforeEval
- a Function that will be called before thescript
is executed.afterEval
- likebeforeEval
, but it will be called after thescript
executed.
TODO
- Add JSDOC
- Add more explanation in
README.md
- Create CLI version
- Create HTTP Server version
- Make more examples
Note
If you find an problem, please report it on the Issue page. or If you have an suggestion and enhancement, please create the Pull Request. We will discuss it first.
Need more example to use uniserv
? try visiting the example folder.
Thanks.