Search code examples
cssnode.jsservermime-typesnext.js

Wrong MIME type with Custom Next.js Server


I'm writing a Next.js app with a custom server.js file and I can't load my css - I keep getting the following in the browser console:

The resource from “http://localhost:3000/_next/
static/development/pages/index.js?ts=1552499710032” 
was blocked due to MIME type (“text/html”) 
mismatch (X-Content-Type-Options: nosniff)

and I don't know why. As far as I can tell I have configured my app as I had done for a previous working version. Here is my next.config.js file:

const withCSS = require('@zeit/next-css');
const withImages = require('next-images');
const path = require('path')
const Dotenv = require('dotenv-webpack')
require('dotenv').config()

module.exports =  withImages(withCSS({
  webpack: config => {
    // Fixes npm packages that depend on `fs` module
    config.node = {
      fs: 'empty'
    }

    config.plugins = config.plugins || []

    config.plugins = [
      ...config.plugins,

      // Read the .env file
      new Dotenv({
        path: path.join(__dirname, '.env'),
        systemvars: true
      })
    ]

    return config
  }
}))

And here is my server.js file:

const express = require('express')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()


const path = require('path');
const options = {
  root: path.join(__dirname, '/static'),
  headers: {
    'Content-Type': 'text/plain;charset=UTF-8',
  }
};


app.prepare().then(() => {
  const server = express()

  server.get('/robots.txt', (req, res) => {
    return res.status(200).sendFile('robots.txt', options)
  });
 
  server.get('/sitemap.xml', (req,res) => {
    return res.status(200).sendFile('sitemap.xml', options)
  });

  server.get('/', (req, res) => {
    return app.render(req, res, '/', req.query)
  })

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

I run my app by using node server.js and I import the css using import "./styles/root.css" (my one and only css file) so no surprises there. What is going wrong?

EDIT: This is trivial enough that it may be a bug. I've opened a report here: https://github.com/zeit/next.js/issues/6647.


Solution

  • You are missing

    server.get('*', (req, res) => {
        return handle(req, res)
    })
    

    in your server.js. your github repo will work fine if you uncomment the above code and restart the server