How to use next-server - 10 common examples

To help you get started, we’ve selected a few next-server examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github traveloka / soya-next / packages / soya-next-scripts / scripts / build.js View on Github external
process.env.NODE_ENV = process.env.NODE_ENV || "production";

require("soya-next/config/default");

process.on("unhandledRejection", err => {
  throw err;
});

const { appDir } = require("soya-next-server/paths");
const build = require("next/dist/build").default;
const buildSoya = require("./utils/build-soya");
const { PHASE_PRODUCTION_BUILD } = require("next/constants");
const loadConfig = require("next-server/dist/server/config").default;

const defaultConf = require("../next.config");
const userConf = loadConfig(PHASE_PRODUCTION_BUILD, appDir);
const conf = defaultConf(userConf);

build(appDir, conf)
  .then(
    () => buildSoya(),
    err => {
      if (err.code !== "MODULE_NOT_FOUND") {
        throw err;
      }
    }
  )
  .catch(err => {
    // eslint-disable-next-line no-console
    console.error(err.stack);
    process.exit(1);
  });
github zeit / next.js / packages / next / build / webpack / plugins / pages-plugin.js View on Github external
compilation.moduleTemplates.javascript.hooks.render.tap('PagesPluginRenderPageRegister', (moduleSourcePostModule, module, options) => {
        const {chunk} = options

        // check if the current module is the entry module, we only want to wrap the topmost module
        if (chunk.entryModule !== module) {
          return moduleSourcePostModule
        }

        // Check if the chunk is a page
        if (!IS_BUNDLED_PAGE_REGEX.test(chunk.name)) {
          return moduleSourcePostModule
        }

        // Match the route the chunk belongs to
        let routeName = ROUTE_NAME_REGEX.exec(chunk.name)[1]

        // We need to convert \ into / when we are in windows
        // to get the proper route name
        // Here we need to do windows check because it's possible
        // to have "\" in the filename in unix.
        // Anyway if someone did that, he'll be having issues here.
        // But that's something we cannot avoid.
        if (/^win/.test(process.platform)) {
          routeName = routeName.replace(/\\/g, '/')
        }

        routeName = `/${routeName.replace(/(^|\/)index$/, '')}`

        const source = new ConcatSource(
          `(window.__NEXT_P=window.__NEXT_P||[]).push(['${routeName}', function() {\n`,
          moduleSourcePostModule,
github zeit / next.js / packages / next / server / on-demand-entry-handler.js View on Github external
if (IS_BUNDLED_PAGE_REGEX.test(e.module.name)) return true

        // No dependencies means this is a top level page.
        // So this is a failed page.
        return e.module.dependencies.length === 0
      })
      .map(e => e.module.chunks)
      .reduce((a, b) => [...a, ...b], [])
      .map(c => {
        const pageName = ROUTE_NAME_REGEX.exec(c.name)[1]
        return normalizePage(`/${pageName}`)
      })

    // compilation.entrypoints is a Map object, so iterating over it 0 is the key and 1 is the value
    for (const [, entrypoint] of compilation.entrypoints.entries()) {
      const result = ROUTE_NAME_REGEX.exec(entrypoint.name)
      if (!result) {
        continue
      }

      const pagePath = result[1]

      if (!pagePath) {
        continue
      }

      const page = normalizePage('/' + pagePath)

      const entry = entries[page]
      if (!entry) {
        continue
      }
github zeit / next.js / packages / next / server / next-dev-server.js View on Github external
async addExportPathMapRoutes () {
    // Makes `next export` exportPathMap work in development mode.
    // So that the user doesn't have to define a custom server reading the exportPathMap
    if (this.nextConfig.exportPathMap) {
      console.log('Defining routes from exportPathMap')
      const exportPathMap = await this.nextConfig.exportPathMap({}, {dev: true, dir: this.dir, outDir: null, distDir: this.distDir, buildId: this.buildId}) // In development we can't give a default path mapping
      for (const path in exportPathMap) {
        const {page, query = {}} = exportPathMap[path]

        // We use unshift so that we're sure the routes is defined before Next's default routes
        this.router.add({
          match: route(path),
          fn: async (req, res, params, parsedUrl) => {
            const { query: urlQuery } = parsedUrl

            Object.keys(urlQuery)
              .filter(key => query[key] === undefined)
              .forEach(key => console.warn(`Url defines a query parameter '${key}' that is missing in exportPathMap`))

            const mergedQuery = {...urlQuery, ...query}

            await this.render(req, res, page, mergedQuery, parsedUrl)
          }
        })
      }
    }
  }
github zeit / next.js / packages / next / build / webpack / plugins / pages-plugin.js View on Github external
compilation.moduleTemplates.javascript.hooks.render.tap('PagesPluginRenderPageRegister', (moduleSourcePostModule, module, options) => {
        const {chunk} = options

        // check if the current module is the entry module, we only want to wrap the topmost module
        if (chunk.entryModule !== module) {
          return moduleSourcePostModule
        }

        // Check if the chunk is a page
        if (!IS_BUNDLED_PAGE_REGEX.test(chunk.name)) {
          return moduleSourcePostModule
        }

        // Match the route the chunk belongs to
        let routeName = ROUTE_NAME_REGEX.exec(chunk.name)[1]

        // We need to convert \ into / when we are in windows
        // to get the proper route name
        // Here we need to do windows check because it's possible
        // to have "\" in the filename in unix.
        // Anyway if someone did that, he'll be having issues here.
        // But that's something we cannot avoid.
        if (/^win/.test(process.platform)) {
          routeName = routeName.replace(/\\/g, '/')
        }
github zeit / next.js / packages / next / server / on-demand-entry-handler.js View on Github external
.filter(e => {
        // Make sure to only pick errors which marked with missing modules
        const hasNoModuleFoundError = /ENOENT/.test(e.message) || /Module not found/.test(e.message)
        if (!hasNoModuleFoundError) return false

        // The page itself is missing. So this is a failed page.
        if (IS_BUNDLED_PAGE_REGEX.test(e.module.name)) return true

        // No dependencies means this is a top level page.
        // So this is a failed page.
        return e.module.dependencies.length === 0
      })
      .map(e => e.module.chunks)
github zeit / next.js / packages / next / server / on-demand-entry-handler.js View on Github external
async ensurePage (page) {
      await this.waitUntilReloaded()
      let normalizedPagePath
      try {
        normalizedPagePath = normalizePagePath(page)
      } catch (err) {
        console.error(err)
        throw pageNotFoundError(normalizedPagePath)
      }

      let pagePath = await findPageFile(pagesDir, normalizedPagePath, pageExtensions)

      // Default the /_error route to the Next.js provided default page
      if (page === '/_error' && pagePath === null) {
        pagePath = 'next/dist/pages/_error'
      }

      if (pagePath === null) {
        throw pageNotFoundError(normalizedPagePath)
      }
github zeit / next.js / packages / next / server / on-demand-entry-handler.js View on Github external
try {
        normalizedPagePath = normalizePagePath(page)
      } catch (err) {
        console.error(err)
        throw pageNotFoundError(normalizedPagePath)
      }

      let pagePath = await findPageFile(pagesDir, normalizedPagePath, pageExtensions)

      // Default the /_error route to the Next.js provided default page
      if (page === '/_error' && pagePath === null) {
        pagePath = 'next/dist/pages/_error'
      }

      if (pagePath === null) {
        throw pageNotFoundError(normalizedPagePath)
      }

      let pageUrl = `/${pagePath.replace(new RegExp(`\\.+(?:${pageExtensions.join('|')})$`), '').replace(/\\/g, '/')}`.replace(/\/index$/, '')
      pageUrl = pageUrl === '' ? '/' : pageUrl
      const bundleFile = pageUrl === '/' ? '/index.js' : `${pageUrl}.js`
      const name = join('static', buildId, 'pages', bundleFile)
      const absolutePagePath = pagePath.startsWith('next/dist/pages') ? require.resolve(pagePath) : join(pagesDir, pagePath)

      page = posix.normalize(pageUrl)

      return new Promise((resolve, reject) => {
        // Makes sure the page that is being kept in on-demand-entries matches the webpack output
        const normalizedPage = normalizePage(page)
        const entryInfo = entries[normalizedPage]

        if (entryInfo) {
github zeit / next.js / packages / next-build / index.js View on Github external
module.exports = async function build({dir, conf, entrypoint, buildid: passedBuildId}) {
  const config = loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)
  const buildId = passedBuildId || await config.generateBuildId().trim() // defaults to a uuid
  const distDir = path.join(dir, config.distDir)

  try {
    await access(dir, (fs.constants || fs).W_OK)
  } catch (err) {
    console.error(`> Failed, build directory is not writeable. https://err.sh/zeit/next.js/build-dir-not-writeable`)
    throw err
  }

  const Bundle = require('parcel/src/Bundle')
  rewriteFileName(Bundle, buildId)

  const Bundler = require('parcel');

  await serverBundler({Bundler, dir, buildId, config, entrypoint})
github zeit / next.js / packages / next / client / router.js View on Github external
export function makePublicRouterInstance (router) {
  const instance = {}

  for (const property of urlPropertyFields) {
    if (typeof router[property] === 'object') {
      instance[property] = {...router[property]} // makes sure query is not stateful
      continue
    }

    instance[property] = router[property]
  }

  // Events is a static property on the router, the router doesn't have to be initialized to use it
  instance.events = _Router.events

  propertyFields.forEach((field) => {
    // Here we need to use Object.defineProperty because, we need to return
    // the property assigned to the actual router
    // The value might get changed as we change routes and this is the
    // proper way to access it
    Object.defineProperty(instance, field, {
      get () {
        return router[field]
      }
    })
  })

  coreMethodFields.forEach((field) => {
    instance[field] = (...args) => {
      return router[field](...args)