Yurii Kramarenko
Yurii Kramarenko

Reputation: 1054

Using node modules in zeit/next.js

I have simple application on isomorphic react (zeit/next.js https://github.com/zeit/next.js). How can I use node modules on server side?

Code example:

import React from 'react'

export default class extends React.Component {
        static async getInitialProps({ req }) {
            const isServer = !!req;
            if (isServer){
                // how!?
            }
            return {
                isServer: isServer
            }
        }

        render() {
            return (
                <div>test</div>
            )
        }
    }

Upvotes: 0

Views: 1854

Answers (2)

pungggi
pungggi

Reputation: 1263

you also may want to use a custom server.js to send some data from the server in the request object.

like

const dev = process.env.NODE_ENV !== 'production'

const { createServer } = require('http')
const { parse } = require('url')
const { readFileSync } = require('fs')
const next = require('next')
const mobxReact = require('mobx-react')
const app = next({ dev })
const handle = app.getRequestHandler()

mobxReact.useStaticRendering(true)

app.prepare()
  .then(() => {
    createServer((req, res) => {
      const parsedUrl = parse(req.url, true)
      req.rules = JSON.parse(readFileSync('./micro/rules.json', 'utf8')).rules
      handle(req, res, parsedUrl)
    })
      .listen(3000, err => {
        if (err) throw err
        console.log('> Ready')
      })
  })

Upvotes: 1

Danilo Miranda
Danilo Miranda

Reputation: 111

You can normally install your npm package

npm install <name package>

And use in your code

import <Componente of package> from '<name package>'

I hope that help!

Upvotes: 0

Related Questions