Is it possible to set breakpoints in NextJS serverside code? I've got a debugger in my getInitialProps and it never breaks at that point. It only breaks when it's ran on the browser, server side breakpoints never seem to catch.
What a beautiful question you asked!
getInitialProps It call when the component is called. Just like componentDidMount in react. The difference is that...
You must send the props it needs before calling.
Otherwise ssr will not work.
This method does not display the console and you must return and display the parameter in the method
static async getInitialProps = () => {
return {custom: 'value'}
}
render() {
return(
<div>
{JSON.stringify(custom)}
</div>
);
}
Just in case this question has not been answered:
getInitialProps in nextjs is a server-side function. So, in VSCode, you will have to start the server (npm run dev) in debug mode in order to "hit" the breakpoints in the server-side code. Likewise, you may launch the client side (browser) in debug mode in order to "hit" the breakpoints in the client-side code.
Related
The documentation says that I can disable server-side rendering by adding 'use client' to the top of files that need to be rendered only client-side.
However, in practice, I've added this header to every file in the project, and I see that both Layout and Page are being rendered server-side.
I can confirm this with a simple page:
'use client';
export default () => {
console.log('SERVER RENDER (page)');
return (
<div>test</div>
);
};
I would expect next dev to not output "SERVER RENDER (page)", but it does.
You don't need to disable server-side rendering (SSR), as it's not enabled by default in Next.js.
It pre-renders every page unless instructed otherwise, using either Static Generation or SSR.
Static Generation. The HTML generated at build time and will be reused at every request.
SSR. The HTML is generated on each request.
Next.js uses Static Generation whenever possible.
In your example, SSR doesn't happen. You're seeing the SERVER RENDER (page) message in terminal because you run it in dev (next dev) mode. In dev mode there is no build done, so the pages are generated on the go. You won't see this message in production mode. See this for more details.
Using use client; directive doesn't change the above, it just tells Next.js that a component is a Client Component, which will still be pre-rendered.
It looks like even if a component is marked 'use client', it will still be pre-rendered.
Client Components enable you to add client-side interactivity to your application. In Next.js, they are prerendered on the server and hydrated on the client. You can think of Client Components as how Next.js 12 and previous versions worked (i.e. the pages/ directory).
https://beta.nextjs.org/docs/rendering/server-and-client-components#client-components
#Nikolai pointed this out correctly, but did not answer how to disable SSR.
However, now that we know that Next 13 behaves the same as 12, we can also apply the same hydration workaround that was used in previous versions.
The TLDR is that you want to wrap your layout in a component that conditionally renders the element based on whether it detects the browser environment, e.g.
const Dynamic = ({ children }: { children: React.ReactNode }) => {
const [hasMounted, setHasMounted] = useState(false);
useEffect(() => {
setHasMounted(true);
}, []);
if (!hasMounted) {
return null;
}
return <>{children}</>;
};
export default ({ children }: { children: React.ReactNode }) => {
return (
<html lang="en">
<head />
<body>
<Dynamic>{children}</Dynamic>
</body>
</html>
);
};
Obviously, make sure you know what you are doing. This is generally not desired behavior, though there are exceptions.
I'm new to Next.js and I'm using it to perform server side rendering on the landing page.
The landing page has: 1 generic component that's the same to every user and 1 component that is specific for each user.
Is it possible to perform server side rendering on the generic component, and client side rendering on the specific one?
Thank you.
Yes, you can do client-rendering for any component in your hierarchy. Client rendering usually means that when the component first renders, it fires off some asynchronous request for data (from an API, etc).
In your SSR page, just have your user-specific component not render anything on the initial render (except maybe some loading UI). Then include a useEffect hook that triggers the API call and sets state (local or global state as appropriate) which will trigger your component to re-render with the user-specific data.
During SSR, only the loading state will render. As soon as the component is mounted, the useEffect will trigger and the user-specific data will load and the component will re-render.
Overly simplistic example:
const UserGreeting = () => {
const [name, setName] = setState();
useEffect(() => {
getUserNameAsync().then((data) => {
setName(data.name);
})
}, [setName])
if (!name) {
return <div>...</div>
}
return (
<div>Welcome, {name}</div>
)
}
To make a page both dynamic and static at the same time is possible.
the solution for dynamic: you have to use react useState then useEffect to send the request after unloading fishing on the client side
but first must use next.js api getStaticProps() make the page static user's first visit
In a Next.js app (full-featured, not next export) that uses React Context for state management and the file-system based router, how can you implement advanced routing?
I want to have preconditions for certain pages, so for instance if you try to load /foo but the Context doesn't have a given property set correctly, it'll route you to /bar.
The actual logic is complex and varies by page, so I'm looking for an approach that's easy to maintain.
Note that these preconditions are not authorization-related, so they do not need to be enforced server-side. It's more like "you need to fill out this form before you can go here."
The use of Context imposes some constraints:
Context must be accessed in a React component or in a custom Hook
Using a custom server for routing is not an option, as that would lose the Context - it has to use client-side routing
The current Context has to be checked (I tried decorating useRouter, but if the Context was changed right before router.push, the custom Hook saw the old values)
Update: It's also good to avoid a flash when the page loads before rerouting happens, so a side goal is to return a loading indicator component in that case.
I believe you can create a HOC and wrapped every pages with you HOC that takes arguments e.g. { redirects: '/foo' }
// pages/bar.tsx
const Page = () => {...}
export default RouteHOC({ redirects: '/foo' })(Page)
the HOC file will be something like this
// hoc/RouteHOC.tsx
const RouteHOC = ({ redirects }) => (WrappedComponent) => {
// you can do your logic here with the context.. even filling up a form here
// too also can.. (like returning a modal first before the real Component).
// useEffect work here too..
const { replace } = useRouter()
// then after you want to replace the url with other page
replace(redirects)
return WrappedComponent
}
This is pretty okay to be maintainable I think. You just create all the logic in HOC and when you want to update the logic - you just have to edit it in 1 file.
Well this is one option I can think of when reading your question - sorry if I misunderstood it in any way. There will always be a better way out there as we all know we can improve and adapt to new situation every seconds :D. Cheers 🥂!!
You can do this.
const Component = () => {
const example = useExample()
return <div id='routes'>
<a href='/example1'>Example 1</a>
{example.whatever && <a href='/example2'>Example 1</a>}
</div>
}
I'm using CodeceptJS and I'm trying to write a custom helper that asserts an text and clicks "OK". This dialog pops up as a iframe modal to consent with cookies.
If I write following steps in my scenario
I.amOnPage('/some-path');
within({frame: '#iframeID'}, () => {
I.see('Headline text for dialog');
I.click('OK');
});
// ...
...my test seems to work just fine.
But when I make an custom helper out of that and configure it properly so I can use it:
const { Helper } = codeceptjs;
class CookieConsent extends Helper {
consentWithCookies() {
const { Puppeteer } = this.helpers;
within({frame: '#iframeID'}, () => {
Puppeteer.see('Headline text for dialog');
Puppeteer.click('OK');
});
}
}
module.exports = CookieConsent;
...and use it as a step:
I.amOnPage('/some-path');
I.consentWithCookies();
// ...
...it doesn't seem to work as the consent dialog doesn't get clicked away as it was when implementing this directly in the scenario. According to some console.log() debugging the within callback doesn't get called at all. Console doesn't throw any errors about undefined within or anything suspicious.
I suspect that using within in a custom helper isn't working or I'm doing something wrong that I can't figure out from the documentation.
This warning at documentation doesn't really clarify when within is being used incorrectly, and using await doesn't help the problem.
within can cause problems when used incorrectly. If you see a weird behavior of a test try to refactor it to not use within. It is recommended to keep within for simplest cases when possible. Since within returns a Promise, it may be necessary to await the result even when you're not intending to use the return value.
iFrames can be a pain to work without when it comes down to automation. There are a number of factors that can make an iFrame unreachable to a framework such as cross-domain iFrames, commonly used for increased security on the content served.
Now to fix your issue, all you have to do is use switchTo() - Docs in CodeceptJS which is a function available for all helpers made available. The order should be
I.switchTo('your iframe');
..... some actions here;
I.switchTo(); // You do this so that you get out of the iFrame context when done
Using Polymer 1.0, I am looking for the best approach to showing a login to a user when the app receives a 401 from the app services.
Using Angular I would be looking at using a httpInterceptor to do this, is there an equivalent in Polymer?
Here's an approach which explicitly routes errors from a service element (using iron-ajax)
<template is="dom-bind" id="app">
<values-service values="{{items}}" on-error="onError"></values-service>
<h1>Items <span>{{items}}</span></h1>
<template is="dom-repeat" items="{{items}}">
<p>{{item}}</p>
</template>
</template>
<script src="app.js"></script>
and my app script
(function (document) {
'use strict';
var app = document.querySelector('#app');
app.onError = function (e) {
console.log('app.onError ' + e.detail.request.status);
};
app.addEventListener('error', app.onError);
})(document);
this works, but as the login is something I want to happen without having to wire up elements specifically
To solve this, I created a component that was used for all my Ajax requests. In that component, listened for 401s from the service calls, and called this.fire('401-found') when found.
Then in my other components, I listened for such an event - in my case, in the main document, popping up a dialog asking the user to log in again.
A slightly better approach would be to have the Ajax component take in parameters to say 'yes fire a 401 event' and 'do not give it the standard 401 event, name call it this' then in each component you could listen for such events and react accordingly.
The answer is catching the error on an outermost element as the events bubble up through the dom
<div on-error="onError">
<values-service values="{{items}}"></values-service>
<other-service></other-service>
...
</div>
and some script (as above)
app.onError = function (e) {
console.log('app.onError ' + e.detail.request.status);
};
when any of the contained services, or any contained elements containing services fire an error, the handler will trigger - I do the relevant checks for a request and a 401 and show my login dialog
I recently made a PR to iron-ajax (which was merged a few days ago) that adds an optional bubbles attribute to accomplish exactly this. When the bubbles attribute is present, iron-ajax's request, response, and error events bubble to window. This means you can have global event listeners on window and handle 401s however you want without any more code duplication that adding bubbles to your iron-ajax calls.
What's more, because it's part of iron-ajax, it is officially supported by the Polymer team.
Here's the official docs.