skip to Main Content

ExpressJS apps work fine on IIS but when i tried to install a NextJS I ran into this error

enter image description here

I Followed the guidelines from this article but it seems like I am missing something.

Project Setup

enter image description here

I have Created app.js as entry point on the root folder containing this code:

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost'
const port = process.env.port || 5000
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, }) // Here i tried including and removing port and hostname with same result
const handle = app.getRequestHandler()

app.prepare().then(() => {
    createServer(async (req, res) => {
        try {
            // Be sure to pass `true` as the second argument to `url.parse`.
            // This tells it to parse the query portion of the URL.
            const parsedUrl = parse(req.url, true)
            const { pathname, query } = parsedUrl

            if (pathname === '/a') {
                await app.render(req, res, '/a', query)
            } else if (pathname === '/b') {
                await app.render(req, res, '/b', query)
            } else {
                await handle(req, res, parsedUrl)
            }
        } catch (err) {
            console.error('Error occurred handling', req.url, err)
            res.statusCode = 500
            res.end('internal server error')
        }
    })
        .once('error', (err) => {
            console.error(err)
            process.exit(1)
        })
        .listen(port, () => {
            console.log(`> Ready on http://${hostname}:${port}`)
        })
})

Then added this web.config file :

<configuration>
<system.webServer>
<handlers>
  <add name="iisnode" path="app.js" verb="*" modules="iisnode" />
</handlers>

<iisnode nodeProcessCommandLine="C:Program Filesnodejsnode.exe" />

<rewrite>
  <rules>
    <rule name="nodejs">
      <match url="(.*)" />
      <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
      </conditions>
      <action type="Rewrite" url="/app.js" />
    </rule>
  </rules>
</rewrite> 

<security>
  <requestFiltering>
    <hiddenSegments>
      <add segment="node_modules" />
      <add segment="iisnode" />
    </hiddenSegments>
  </requestFiltering>
</security>
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>

and Edited the package.json scripts as following :

"scripts": {
"dev": "node app.js",
"build": "next build",
"start": "NODE_ENV=production node app.js",
"lint": "next lint"
},

Then I run the build command and create a site on IIS with basic settings

enter image description here

The app seems to work fine when I run "npm run dev" from visual studio terminal.
But I get 404.2 error when I run from IIS.
please advice.

2

Answers


  1. I saw you are facing 404.2 error, you could try the web.config below, if it not works, you can follow the official doc to check the issue.

    Change your code like below:

    <configuration>
      <system.webServer>    
        <rewrite>
          <rules>
            <rule name="myapp">
              <match url="/*" />
              <action type="Rewrite" url="app.js" />
            </rule>
          </rules>
        </rewrite>
    
        <iisnode node_env="production" nodeProcessCommandLine="&quot;C:Program Filesnodejsnode.exe&quot;" interceptor="&quot;%programfiles%iisnodeinterceptor.js&quot;" />
    
      </system.webServer>
        <location path="" overrideMode="Deny">
            <system.webServer>
        <handlers>
          <add name="iisnode" path="app.js" verb="*" modules="iisnode" />
        </handlers>
            </system.webServer>
        </location>
    </configuration>
    

    I have downloaded and deployed the project, it works fine.

    enter image description here

    Login or Signup to reply.
  2. I’ve had the same issue and I think the problem is in a pipe used by iisnode instead of a numeric port.

    A simple solution to resolve this issue is to create http-proxy server and next.js server.

    const { createServer } = require('http');
    const { createProxyServer } = require('http-proxy');
    const { parse } = require('url');
    const next = require('next');
    
    const hostname = 'localhost';
    const nextJsPort = 12007;
    
    const startNextJsServer = () => {
        // your current code starting next.js server, but using nextJsPort variable as port
    };
    
    const startProxyServer = () => {
        const proxy = createProxyServer({});
    
        const httpProxyPort = process.env.PORT;
        const httpProxyTargetServer = `http://${hostname}:${nextJsPort}`;
    
        createServer((req, res) => {
            proxy.web(req, res, { target: httpProxyTargetServer }, err => {
                console.error('Error occurred handling redirection', err);
                res.statusCode = 500;
                res.end('Internal proxy server error');
            });
        }).listen(httpProxyPort, () => {
            console.log(`Proxy server ready on ${httpProxyPort}`);
        });
    };
    
    startNextJsServer();
    startProxyServer();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search