Is there a way to redirect a NuxtJs application using Express server? - express

I have a NuxtJs application initialized with Express server using npx create-nuxt-app <project-name>. It is set for server-side rendering.
Express has access to NuxtJs middleware like so. ( Which comes by default when Nuxt app is created )
app.use(nuxt.render)
Now I have created a different route file in server side that handles API routes. This route works as I can access data using Axios. I have added this route right before the above code, like this. ( API routes don't work if it is added after )
app.use('/api', apiRoutes)
app.use(nuxt.render)
There is a route where, after some operation, I need to redirect the application to another page. I tried using res.redirect('/some-route'), which is an Express way for redirection but that didn't work.
Am I missing something here? Is there some other way we do redirection from server side in Nuxt application that I'm totally unaware of?

Finally found the way to redirect from the back-end.
res.writeHead(301, { Location: url })
res.end()
Here is the link to Nuxt GitHub issue comment for detailed example using server middleware.
Alternatively, you could respond with desired value to the font-end and based on the value received, you can re-direct from the front-end.

Related

How do I connect an ExpressJS backend to a SvelteKit frontend?

I'm trying to create an app that uses ExpressJS as the backend and SvelteKit as the frontend. Express will be the entry point for the web server, so for example /api/ requests will be routed to ExpressJS and anything other than this will be sent to the SvelteKit frontend.
I'm using the node adaptor for SvelteKit and have found that it makes a fully contained node server in '/build/index.js' for the SvelteKit application.
However, this is where I'm stuck now and I'm not sure how to route the requests to the frontend through the Express app. Any help would be much appreciated. I'd ideally like to have this contained within one project.
Link to the node adaptor: https://github.com/sveltejs/kit/blob/master/packages/adapter-node/README.md
I think I worked it out! These two lines solve this in the express app:
import { handler } from './build/handler.js';
app.use(handler);
This is the perfect answer but sometime if you new to express and svelte, then always use app.use(handler) after express routes defined. Otherwise express routes wont work.
EX -
You might get errors like this, i posted because it might save some people time.
https://i.stack.imgur.com/mLDTv.png

NextJS API route conflict

I have been transitioning to NextJS from CRA. I'm re-implementing authentication using SSR, and I would like to use NextJS built-in API routes to set HTTPOnly cookies.
There is a weird problem where my backend base URL is https://somesite.com/api and my frontend's - https://somesite.com/. This means that NextJS built-in API routes will be in conflict with my own backend.
I have been researching online and couldn't find any way on changing routing in NextJS, and I don't want to change base URL of my backend, since there are other services depending on it.
Has anyone had the same issue? How can I resolve this issue?
Try next.js rewrite
Rewrites allow you to map an incoming request path to a different destination path. Docs
Check Live Example here: https://stackblitz.com/edit/nextjs-rewrite
If Path is /api it'll point to JSON placeholder APIs.(ex. /api/todos)
module.exports = {
async rewrites() {
return [
{
source: '/api/:slug*',
destination: 'https://jsonplaceholder.typicode.com/:slug*'
}
];
}
};

Accessing the request object in nuxtJS module

I'm trying to create a nuxtJS module to make some changes to the routes based on the URL or request, i simply want to access the request.header.host inside a nuxtJS module but I'm unable to get it, i tried to check it process.server, this, context but unable to get the request object, i just want to get the full domain only, so how can I do that?
You can only get the hostname in the Browser JavaScript not internally in running nuxt app. As for nuxt app, it is running locally on the server (for example http://localhost:8080).
The information regarding hostname is present in services like Nginx/Apache.
Solution (One of them):
Use #nuxt/dotenv and store hostname in the environment variables:
hostname=example.com
then use wherever you want in your nuxt application with process.env.hostname

Returned data being rendered instead of page structure in Nuxt

I'm trying to return data as JSON from the express server for a route. The data returns fine but when i open the NUXT page on the browser than the JSON data gets outputted instead of the page HTML.
Note the express route is the same as the page route. I know the routes are conflicting with each other. Do i need to have the server and front-end on different ports? Is there anything wrong i'm doing here?
Thanks
To avoid conflicts such as that you should use a prefix like /api/ or /api/v1/ something like that
In nuxt.config.js you need to define your server middleware
serverMiddleware: ["~/api/index.js"]
That file is your server. At the bottom you need to export it like this:
module.exports = {
path: "/api",
handler: app
}
Note here: app is your express app if you use express.js.
This here: const app = express();
If everything worked your root of your API should be available under host:port/api/
you cant do this if the routes for backend and frontend exactly same. this is route rules that they have to be unique and its not backend or frontend issue for e.x. you can have two routes with same url in express(api), nuxt too.
if we say the application for example is post office, the route are path to a house address (controller or action) so we can have two path to get the a house but its confusion have a same path(url or route) and different houses.
simple solutions:
as you said make the api and front separate with different ports or different domains or even have a prefix for your express routes
in express handle all of them, means return view or page with data needed instead of json data

Dynamically change API route for SPA

I am currently building a SPA app using Vue.js and webpack to do our bundling. The backend API is built with .Net Core. When running locally, the Vue app is hitting localhost on the backend. I need to be able to change the route of the API dynamically based on the environment. Is there a way to do this without having to do a big switch statement that considers the current url? A requirement is that we are not allowed to change the webpack bundle for different environments, in other words, once it is bundled, it has to stay bundled. I have tried to pass static config files through to the bundle and dynamically change them based on the environment, but unfortunately that does not work, as it hits the values that were originally in them.
webpack dev server has a proxy capability. You could use this to proxy to your locally running backend when developing.
https://webpack.js.org/configuration/dev-server/#devserver-proxy
e.g. you can point anything from '/api' to 'localhost:8888/api' with the config.
Is your app the backend running on the same url when deployed? If not, you'll likely need a reverse proxy to pass along the requests to the backend.
You can use an axios interceptor so you only have that switch in one place:
axios.interceptors.request.use(config => {
// check location.host name and append the backend url you want
});
see https://github.com/axios/axios#interceptors
However, this is a little dangerous as the URLs in your switch statement will be strings, and therefore all of your environment URLs can be pulled out of your code even if minified/concatenated.
Another option is to add some sort of endpoint to the server your client side code is hosted, and when you start your app, query for that configuration.