Home > Back-end >  Css and Js not working after deploying the next react project to server side
Css and Js not working after deploying the next react project to server side

Time:05-15

I have React next and node js projects I want to deploy that project in one port. For that, I created ts file to js and ran the. next folder to the backend side. Now my API and frontend code working at the same port. for that, I am using express. But the issue is that it does not take any js and CSS my code is that :

app.use(express.static(path.join(__dirname, './server/.next/')));

app.get('*', (req, res) => {
  res.sendFile(__dirname   '/server/.next/server/pages/index.html');
})

when I open the index.js file i the next folder all css and js paths are created in this way:

  <link rel="preload" href="/_next/static/css/33698e28f26f4e47.css"  

my css is working if manually i will remove _next in the front of static/css/ 33698e28f26f4e47. But I can't remove it manually because of index.js created by npm run build command

CodePudding user response:

You should change base path in your next.config, because I think you don't have "/_next/static/css/" path in your node.js root.

module.exports = {
  assetPrefix: 'assetPrefixPath',
  ...
  publicRuntimeConfig: {
    ...
    basePath: 'basePath',
    ...
  },
}

CodePudding user response:

its works for me I used this code in the index.js:-

import next from "next";

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const port = process.env.PORT || 3000;

(async () => {
 try {
   await app.prepare();
   const server = express();
   server.all("*", (req: Request, res: Response) => {
    return handle(req, res);
  });
   server.listen(port, (err?: any) => {
  if (err) throw err;
  console.log(`> Ready on localhost:${port} - env 
   ${process.env.NODE_ENV}`);
  });
  } catch (e) {
   console.error(e);
   process.exit(1);
 }
 })();
  • Related