Next.js: Using node modules

Created on 1 Nov 2016  路  10Comments  路  Source: vercel/next.js

Hello!

I'm trying to use node module in my page.

import fs from 'fs'
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>
            )
        }
    }

But it doesn't work. What I need to do to use node modules in my page?

Most helpful comment

You can in your server make a HTTP request to an API who use the fs module and get the content of a file (or do whatever you want to do) and return you the result, then you don't need to use the fs module directly.

All 10 comments

@Dalas Node modules are not available to your component when rendered client-side.

@dstreet how can I access them on server side?

@Dalas The short answer is you can't. Currently, your best bet would be to find some isomorphic implementation of the module you need. However, I don't know of any for fs.

@dstreet thank you.

You can in your server make a HTTP request to an API who use the fs module and get the content of a file (or do whatever you want to do) and return you the result, then you don't need to use the fs module directly.

const isServer = 'undefined' !== typeof window
if (isServer) {
  const fs = require('fs')
  ...
}

I wonder if this kind of workarounds doesn't work.

@nkzawa that fails during the bundling. It works perfectly well for modules like '
path, but not fs, which requires an actual filesystem.

const isServer = typeof window === 'undefined'
if (isServer) {
  const fs = eval('require("fs")')
  ...
}

This is probably bad right? Works though..
Need similar workaround for firebase-admin on server

You can exclude modules from bundling by the setting of webpack like the following on v2 (you can try with next@beta now).

// next.config.js
module.exports = {
  webpack (config) {
    config.externals = config.externals || {}
    config.externals.foo = 'foo'
    return config
  }
}

I was also trying to get firebase-admin working, and ended up needing to use a custom node server: next-example

Was this page helpful?
0 / 5 - 0 ratings