Nuxt SSR blog still calling API endpoints to get blog posts even thought its setup to be SSR - server-side-rendering

been playing around with a simple blog built with JSONPlaceholder and Nuxt.js
Everything seems fine, I've got an archive and single blog posts working fine but when deployed on Netlify I can see that the browser is still doing API calls to JSONPlaceholder even though all the pages are built static and I can see they already have the content within the HTML.
I used the routes method within generate in the nuxt config to create the 100 html files based upon the JSONPlaceholder /posts results.
Here's the Netlify link: REMOVED.
And a public repo: https://bitbucket.org/oneupstudio/api-test/src/master/
Anything I've missed?

Nuxt.js doesn't support 'full static generation' yet, check this RFC.
For now, you can use this module in order to make your JSON requests static.

Nuxt currenty supports proper static generation of websites. Although one has to be aware of payload param in asyncData. So if payload is present that indicates that static generator is at work and no api calls should be made in this case:
async asyncData ({ params, error, payload }) {
if (payload) return { user: payload }
else return { user: await backend.fetchUser(params.id) }
}
Read more on this here.
RFC mentioned by #DreadMinder will further improve on this, but you can already do full static websites with Nuxt.

Related

Gatsby Deployment Issue

I have a javascript file hubspot.js on src/api folder of my gatsby project which become functions automatically with paths based on their file name (according to Gatsby Documentation).
This API is called when submitting one form which should create a contact in hubspot.
When I run the project in development, it successfully returns the response and contact is created. But, while using "serve public" to test in production, it returns:
POST http://localhost:3000/api/hubspot 404 (Not Found)
and also in deploying using nginx configuration, it returns 405 error.
I also have another api function called status which is like this and is a GET api.
export default function handler(req, res) {
res.status(200).json({ status: 'ok' });
}
Even this function is not called and returns not found error.
I don't have any backend as gatsby can handle that part by itself, as described here.
Functions let you build dynamic applications without running servers. Submit forms, authenticate users, securely connect to external services, build GraphQL/REST APIs, and more.
Gatsby Function
So, even in production, this must be handled and the api should be called when the form submits or when I make a GET request to /api/status.
But, all I am getting is 404 not found and 405 error.

Hiding Storyblok API-Key

I'm using Next.js with Storyblok and recently made use of the react-next-boilerplate.
I noticed that they put the preview token in the _app.js, so essentially publish it:
storyblokInit({
accessToken: "your-preview-token",
use: [apiPlugin],
components,
});
If I use an environment variable instead, which isn't available on the client, I get the error
You need to provide an access token to interact with Storyblok API
in the client. That's because (I think) my components use StoryblokComponent, which makes use of the global Storyblok state. So I wonder:
Should I ignore this error, as I don't plan to interact with the Storyblok API other than using it for component rendering (all the data comes from the server, as far as I understand the concept of static site generation), and component rendering seems to be still working?
Should I just publish the preview token?
Should I create two tokens, one for the server and one for the client?
Setting the token to process.env.STORYBLOK_API_KEY || "NULL" (where "NULL" can be anything except the empty string) also works (no more errors) but seems like a weird solution.
I don't really understand why they combine these two things, component rendering and data fetching, in the same function.
I would use a .env.local file and populate it with:
STORYBLOK_API_KEY=your-preview-token
To use the environment variable inside _app.js you have to pass it to next.config.js like this:
module.exports = {
env: {
STORYBLOK_API_KEY: process.env.STORYBLOK_API_KEY,
}
}
Source: https://nextjs.org/docs/basic-features/environment-variables

What path should I use for Meteor's Webapp API?

I'm using Meteor v1.9 Webapp API to have my app listen to HTTP requests, specifically from a link to the app itself from a website, let's say example.org.
The documentation says to use
WebApp.connectHandlers.use([path], handler)
Where the [path] is defined as such:
path - an optional path field. This handler will only be called on
paths that match this string. The match has to border on a / or a ..
For example, /hello will match /hello/world and /hello.world, but not
/hello_world.
My question:
Let's say my meteor application is hosted on abc.com and the POST data being sent over to it is from example.org (where the link to abc.com is as well).
For the [path] argument mentioned above, in this case, should I have it as "/example" since example.org is where my app is listening to requests from (getting the POST data)? Or does it have to be a different format? I tried the former, but it doesn't seem to be working for it, so I'm trying to find the root of the issue.
Additional information that might be useful: I know it says 'optional' so I tried omitting it, but when I tested it out via 'meteor run' where it runs off of localhost:3000, it just yielded a blank page, with no errors and a success sent back, probably because it uses a GET request instead of POST.
My code for the webapp in my meteor application is as follows:
WebApp.connectHandlers.use("/[example]", async (req, res, next) => {
userName = req.body;
res.writeHead(200);
res.end();
});
Also technically my meteor application is built/bundled and deployed as a Node.js application on the website, but that shouldn't affect anything regarding this as far as I could tell.
That path is the path (part of the URL) on your meteor server. So in your example, for instance,
WebApp.connectHandlers.use("/example", async (req, res, next) => {
userName = req.body;
res.writeHead(200);
res.end();
});
means that you will need to send your POST requests to abc.com/example.

Next.JS - localhost is prepended when making external API call

I got a simple Next app where I'm making an external API call to fetch some data. This worked perfectly fine until a couple days ago - when the app is making an API request, I can see in the network tab that the URL that it's trying to call, got Next app's address (localhost:3000) prepended in front of the actual URL that needs to be called e.g.: instead of http://{serverAddress}/api/articles it is calling http://localhost:3000/{serverAddress}/api/articles and this request resolves into 404 Not Found.
To make the API call, I'm using fetch. Before making the request, I've logged the URL that was passed into fetch and it was correct URL that I need. I also confirmed my API is working as expected by making the request to the expected URL using Postman.
I haven't tried using other library like axios to make this request because simply it doesn't make sense considering my app was working perfectly fine only using fetch so I want to understand why is this happening for my future experience.
I haven't made any code changes since my app was working, however, I was Dockerizing my services so I installed Docker and WSL2 with Ubuntu. I was deploying those containers on another machine, now both, the API I'm calling and Next app are running on my development machine directly when this issue is happening.
I saw this post, I confirmed I don't have any whitespaces in the URL, however, as one comment mentions, I installed WSL2, however, I am not running the app via WSL terminal. Also, I've tried executing wsl --shutdown to see if that helps, unfortunately the issue still persists. If this is the cause of the issue, how can I fix it? Uninstall WSL2? If not, what might be another possible cause for the issue?
Thanks in advance.
EDIT:
The code I'm using to call fetch:
fetcher.js
export const fetcher = (path, options) =>
fetch(`${process.env.NEXT_PUBLIC_API_URL}${path}`, options)
.then(res => res.json());
useArticles.js
import { useSWRInfinite } from 'swr';
import { fetcher } from '../../utils/fetcher';
const getKey = (pageIndex, previousPageData, pageSize) => {
if (previousPageData && !previousPageData.length) return null;
return `/api/articles?page=${pageIndex}&limit=${pageSize}`;
};
export default function useArticles(pageSize) {
const { data, error, isValidating, size, setSize } = useSWRInfinite(
(pageIndex, previousPageData) =>
getKey(pageIndex, previousPageData, pageSize),
fetcher
);
return {
data,
error,
isValidating,
size,
setSize
};
}
You might be missing protocol (http/https) in your API call. Fetch by default calls the host server URL unless you provide the protocol name.
Either put it into env variable:
NEXT_PUBLIC_API_URL=http://server_address
Or prefix your fetch call with the protocol name:
fetch(`http://${process.env.NEXT_PUBLIC_API_URL}${path}`, options)

How to fix "Callback URL mismatch" NextJs Auth0 App

I am using Auth0 NextJs SDK for authentication in my NextJS App. I am following this tutorial https://auth0.com/blog/introducing-the-auth0-next-js-sdk/. In my local machine, everything works fine.
The configuration for Auth0 in my local server:
AUTH0_SECRET=XXXXX
AUTH0_BASE_URL=http://localhost:3000
AUTH0_ISSUER_BASE_URL=https://myappfakename.us.auth0.com
AUTH0_CLIENT_ID=XXXX
AUTH0_CLIENT_SECRET=XXXX
In the Auth0 Dashboard, I added the following URLs :
Allowed Callback URLs: http://localhost:3000/api/auth/callback
Allowed Logout URLs: http://localhost:3000/
My local app works locally fine.
I uploaded the app on Vercel. And changed the
AUTH0_BASE_URL=https://mysitefakename.vercel.app/
In Auth0 Dashboard, updated the following information:
Allowed Callback URLs: https://mysitefakename.vercel.app/api/auth/callback
Allowed Logout URLs: https://mysitefakename.vercel.app
I am getting the following error:
Oops!, something went wrong
Callback URL mismatch.
The provided redirect_uri is not in the list of allowed callback URLs.
Please go to the Application Settings page and make sure you are sending a valid callback url from your application
What changes I should make it works from Vercel as well?
You can try to check if vercel isn't changing the url when redirecting to auth0. Your configurations seems good to me. The error is very explicit though. I think a good option should be to verify that the redirect (if handled by vercel) is doing with the same url as auth0 expects.
And don't forget to add the url you're currently on when performing the callback. Are you in https://mysitefakename.vercel.app/api/auth/callback when the callback is executed? (call auth0).
you have to change your base url in the env.local file
AUTH0_BASE_URL=https://mysitefakename.vercel.app/
you can also make two more env files namely env.development and env.production and set different base urls for different cases so that the correct base url is automatically loaded depending on how ur web app is running.
You need to add handleLogin under api/auth/[...auth0].js and that will solve it:
import { handleAuth, handleLogin } from '#auth0/nextjs-auth0';
export default handleAuth({
async login(request, response) {
await handleLogin(request, response, {
returnTo: '/profile',
});
},
});
Don't forget to also add allowed callback url in [Auth0 Dashboard]: https://manage.auth0.com/dashboard for your hosted app for both local and hosted instance:
http://localhost:3000/api/auth/callback, https://*.vercel.app/api/auth/callback

Resources