npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

egg-ssr-pages

v1.3.3

Published

Create roe/egg route definitions to host server-side rendered pages by using next/nuxt

Downloads

15

Readme

Build Status Coverage

egg-ssr-pages

Create roe/egg route definitions to host server-side rendered pages by using next or others.

By using next(the default renderer) as the renderer, your roe/egg application should has a next property on the instance.

Install

$ npm i egg-ssr-pages

Usage

app/router.js

const ssrPages = require('egg-ssr-pages')
const pages = {
    // Then if we can access the pages/index.js by
    //   visiting the page http://localhost:8888/en-US
    '/:lang': 'index'
}

const config = {
  cache: {
    maxAge: 0
  },
  guard: ssrPages.memoryGuardian({
    max: 100
  }),

  // By default, it renders pages by using next
  // renderer: 'next'
}

module.exports = ssrPages(pages, config)
  • guard guardian is used to validate the each result of server-side rendered pages, and fetch staled value from cache when the server fails to render the page to improves availability.

  • cache to specify max-age of the cache-controll header.

Override default SSRConfig for a certain pagePath

module.exports = ssrPages({
  '/:lang': 'index',

  // We can override a certain property of `SSRConfig` by
  //   defining a new value in each `PageDef`
  '/about': {
    entry: 'about',
    cache: {
      // http://localhost:8888/about
      // -> max-age: 1h
      maxAge: 60 * 60 * 1000
    }
  }
}, {
  cache: {
    maxAge: 0
  }
})

Custom middleware for a certain entry

module.exports = ssrPages({
  '/:lang': {
    entry: 'index',
    middleware: [myCustomMiddleware]
  }
})

Or

module.exports = ssrPages({
  '/:lang': [
    myCustomMiddleware,  // <- koa middleware
    // <- We can define more koa middlewares here
    'index'   // <- entry
  ]
})

Different entries for desktop and mobile devices

const diverge = (desktopEntry, mobileEntry) => ctx =>
  isMobileUserAgent(ctx.headers['user-agent'])
    ? mobileEntry
    : desktopEntry

module.exports = ssrPages({
  '/': diverge('index', 'mobile-index')
})

ssrPages(pages, config: SSRConfig)

  • pages {[path: string]: PageDef} pages
  • config SSRConfig the default ssr configurations

Returns a roe/egg router function which accepts app as the only one parameter.

type EntryGetter = function (ctx): string

type PageDef =
  // Just an entry
  string
  | EntryGetter
  // An entry and koa middleware functions for the entry
  | [...Array<Function>, string]
  | ObjectPageDef
// So that we can override the default ssr configurations
interface ObjectPageDef extends OptionalSSRConfig {
  entry: string | EntryGetter
}
interface OptionalSSRConfig {
  // Disable CDN cache by setting to `false`,
  // Defaults to `false`
  cache?: CachePolicy | false
  // Set the `guard` to `false` to disable server-side guardians.
  // - GuardPolicy: your custom policy
  // - `false`(the default value): turn off the guardians
  guard?: GuardPolicy | false,

  // New in 1.1.0
  // Set one or more middlewares for all entries or for a certain entry.
  middleware?: Function | Array<Function>
}

// Preflight checker is used to make sure
//  if the prerequisites are installed or configured,
//  such as egg plugins and extentions
type PreflightChecker = (app): Object | undefined throws Error

interface SSRenderer {
  precheck: PreflightChecker
  async render (ctx, pagePath): string throws Error
}

interface SSRConfig extends OptionalSSRConfig {
  // Method to render the page
  // - SSRenderer: your custom renderer
  // - string: the name of built-in renderers: 'next'
  // Defaults to `'next'`
  renderer: SSRenderer | string = 'next'
}
interface CachePolicy {
  // max-age of cache-control in milliseconeds
  maxAge: number
}
interface GuardPolicy {
  // Preflight checking to see
  //   if the `app` (roe/egg instance) meets certain requirements.
  //   if not, an error could be thrown inside this function.
  // If the function returns an object,
  //   then the object will be used to extend the koa context object,
  //   so that we can access them from all methods below.
  precheck? (app): Object | undefined throws Error

  // Generates the cache key
  key (ctx): string

  // If this function is rejected or returns `false`
  // then it will goes into `fallback`
  async validateSSRResult? (ctx, key, html, time): boolean throws Error

  // If `render` method has been invoked and validated successfully,
  //    `onSuccess` will be called and skip all the following.
  // Most usually, all logic inside `onSuccess` should be catched,
  //   or if there is an error or rejection,
  //   it will goes to `fallback`
  async onSuccess? (ctx, key, html): void

  // If `fallback` succeeded to return a string,
  //   the string will be used instead of the return value of `render`
  async fallback (ctx, key, html, error): string throws Error
  • ctx KoaContext the koa context, if precheck returns an object, then it will be the extended koa context which has the return value as its own properties
  • key string the key generated by GuardPolicy::key
  • html string | undefined the html content which rendered by SSRConfig::render
  • time number the milliseconds how much the renderer takes to render the page
  • error Error | null

Built-in guardian ssrPages.memoryGuardian(options)

The built-in guardian to cache successfully rendered result in an LRU cache instance with ${hostname}/${pathname} as the key, and try to return the cached value if the request fails to render in the future.

License

MIT