I have my project build in next.js 14.2
and hosted on heroku under my-app.com
Now I want to serve a external site as landingpage content my-landingpage.com
without the user noticing that the domain changed (the domain in the brower shall still be my-app.com
). As soon as the user navigates further, the content from my next.js project shall be reached (e.g. my-app.com/login). Is that possible?
I know how I can redirect the root directory to the external site but then in the brower it says my-landingpage.com
but I want to keep my-app.com
.
either in next.config.js
module.exports = {
async redirects() {
return [
{
source: '/',
destination: 'https://my-landingpage.com'
},
]
},
};
or in middleware.js
import { NextResponse } from "next/server";
export function middleware(request) {
if (request.nextUrl.pathname === '/') {
const externalLandingPageURL = 'https://test.de';
return NextResponse.rewrite(new URL(externalLandingPageURL, request.url), 301);
}
}
Use a reverse proxy setup.
npm install http-proxy-middleware
Then in root
create server.js
:
const { createProxyMiddleware } = require('http-proxy-middleware');
const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
/* proxy for the landing page */
server.use(
'/',
(req, res, next) => {
if (req.path === '/') {
/* only proxy the root path */
createProxyMiddleware({
target: 'https://my-landingpage.com',
changeOrigin: true,
pathRewrite: {
'^/$': '/', /* rewrite the root path to the root of the */ target
},
})(req, res, next);
} else {
next(); /* pass other paths to the next middleware */
}
}
);
/* Handle other routes with Next.js */
server.all('*', (req, res) => {
return handle(req, res);
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${PORT}`);
});
});
Of course you have to make all necessary updates (package...)
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
And then you can deploy to Heroku.