Next.js: Node native modules in _document

Created on 16 Aug 2017  路  1Comment  路  Source: vercel/next.js


As far as I can tell, a custom <Document /> is only ever run in Node.js / SSR. If that's the case, why wouldn't importing native node modules be allowed?

edit: Is this because of the way javascript is compiled through webpack with emit-file-loader?

  • [x] I have searched the issues of this repository and believe that this is not a duplicate.

Expected Behavior

import fs from 'fs';

in _document.js should compile

Current Behavior

Build fails, suggesting installing fs

Steps to Reproduce (for bugs)

  1. import fs from 'fs' in a custom document.

Context

I'm working on flushing styled-components SSR output to a link tag, to enable potentially putting cloudfront in front of it and serve <link> tags rather than inline styles.

Your Environment


| Tech | Version |
|---------|---------|
| next | 3beta |

Most helpful comment

Add a next.config.js file to your root directory with the following content:

module.exports = {
  webpack(config) {
    config.externals = config.externals || {}
    config.externals.fs = 'fs'
    return config
  },
}

Make sure to access fs only server side:

if (typeof window === 'undefined') {
  console.log(fs)
}

EDIT: I have removed the require('fs') part. The import statement works fine.

>All comments

Add a next.config.js file to your root directory with the following content:

module.exports = {
  webpack(config) {
    config.externals = config.externals || {}
    config.externals.fs = 'fs'
    return config
  },
}

Make sure to access fs only server side:

if (typeof window === 'undefined') {
  console.log(fs)
}

EDIT: I have removed the require('fs') part. The import statement works fine.

Was this page helpful?
0 / 5 - 0 ratings