I have implemented the server maintaining all the required things following the https://nextjs.org/docs/app/building-your-application/configuring/custom-server and other resource available. My application is working fine in the localhost but getting problems when I deploy it on the shared hosting. all the routes mentioned in the config.matcher are showing not-found page instead of its page. I have tried using the hostname for the production for example: example.com, 120.320.245.43 (shared IP address), but it is not working. i have added the code in this repo https://github.com/robiulhr/next-middleware-custom-server-issue/
here is my server.js file for the custom server
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
require('dotenv').config();
const dev = process.env.NODE_ENV !== 'production'
const hostname = process.env.HOST_NAME || 'localhost'
const port = process.env.PORT || 3000
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port })
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}`)
})
})
and this is the middleware.js file
import { NextResponse } from 'next/server'
// Array of paths to check against
const privateRoutes = ['/account', "/orders", "/wishlist", "/password/update"];
const authRoutes = ["/login", '/register'];
const adminRouteMatcher = "/admin";
export async function middleware(request) {
try {
const refreshToken = request.cookies.get('refreshToken')?.value
const isAuthenticated = request.cookies.get('is_auth')?.value
const user_role = request.cookies.get("user_role")?.value;
const path = request.nextUrl.pathname;
if (refreshToken && isAuthenticated) {
if (path?.startsWith(adminRouteMatcher) && user_role !== "admin") {
return NextResponse.redirect(new URL('/', request.url));
}
if (authRoutes.includes(path)) {
return NextResponse.redirect(new URL('/account', request.url));
}
}
if ((!refreshToken || !isAuthenticated) && (privateRoutes.includes(path) || path?.startsWith(adminRouteMatcher))) {
const response = NextResponse.redirect(new URL(`/login?ref=${path.slice(1)}`, request.url));
response.cookies.delete("is_auth");
response.cookies.delete("accessToken");
response.cookies.delete("user_role");
response.cookies.delete("refreshToken");
return response;
}
return NextResponse.next()
} catch (error) {
console.error('Error occurred while checking authentication:', error);
// Handle the error, maybe return a response with 500 status code
return NextResponse.error();
}
}
export const config = {
matcher: ['/account', "/orders", "/wishlist", '/admin/:path*', '/login', '/register']
}