I want to run my nextjs app on https in cpanel, but It's not working! But there is no problem on http and it runs. Also, SSL is installed on the domain in cPanel and is valid.
this is server.js, stratup file at node js application in cpanel :
const https = require("https");
const { parse } = require("url");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 3000;
// when using middleware `hostname` and `port` must be provided below
const nextApp = next({
dev
});
const nextHandler = nextApp.getRequestHandler();
nextApp.prepare().then(async () => {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
//const app = express();
//const server= https.createServer(app);
const server = https.createServer(async (req, res) => {
// res.send("Hello World");
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === "/a") {
await nextApp.render(req, res, "/a", query);
} else if (pathname === "/b") {
await nextApp.render(req, res, "/b", query);
} else {
await nextHandler(req, res, parsedUrl);
}
});
//app.get('/hello', async (_, res) => {
// res.send('Hello World')
// });
server.listen(port, (err) => {
//res.send('Hello World');
console.log(`> Ready on http://localhost:${port}`);
console.log(server.address());
});
});
`
And after running and after a lot of time, the following error occurs :
Request Timeout
I was able to find the problem.
The 500 error only occurred in HTTPS mode in cpanel, which occurred in the next-intl library.
I was able to solve the problem by using redirect:
in file middleware.ts
const locales = ['default','en', 'es', 'fr'];
const defaultLocaleReal = 'en';
const defaultLocaleFake = 'default';
const intlMiddleware = createMiddleware({
locales,
localeDetection: false,
defaultLocale: defaultLocaleFake,
});
const PUBLIC_FILE = /\.(.*)$/;
export default function middleware(req: NextRequest) {
const { pathname } = req.nextUrl.clone()
const pathnameIsMissingLocale = locales.every(
(locale) => !PUBLIC_FILE.test(pathname) &&
!pathname.includes('/api/') && !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
)
const cookie = req.cookies.get('NEXT_LOCALE')?.value;
if (pathnameIsMissingLocale) {
const locale = cookie ? ((cookie == defaultLocaleFake) ? defaultLocaleReal : cookie) : defaultLocaleFake;
const url = `https://example.com/${locale}${pathname}${req.nextUrl.search ? `${req.nextUrl.search}`:''}`;
return NextResponse.redirect(
new URL(url)
)
}
return intlMiddleware(req);
}