-
Update: We’re excited to announce Next.js 13, which includes the new Inside the You can leave feedback here: #41745 |
Beta Was this translation helpful? Give feedback.
Replies: 39 comments 79 replies
-
As long as you don't implement getInitialProps, getStaticProps, getServerProps in _app. It still has the usefulness of adding persistent components for SPA apps. |
Beta Was this translation helpful? Give feedback.
-
It'll be introduced later, but we need to figure out the semantics as we really don't want getServerSideProps in _app to opt-out static generation for all pages |
Beta Was this translation helpful? Give feedback.
-
So without |
Beta Was this translation helpful? Give feedback.
-
Any update for this issue? I need to read the data in cookie and use it for all pages. So |
Beta Was this translation helpful? Give feedback.
-
I'm running into this same issue and I've yet to find a way to make it work. All I want is to expose All I want is to read the |
Beta Was this translation helpful? Give feedback.
-
I'm looking into this issue as well. Looking at Profile.getInitialProps = async ({ req, res }) => {
if (typeof window === 'undefined') {
const session = await auth0.getSession(req);
if (!session || !session.user) {
res.writeHead(302, {
Location: '/api/login'
});
res.end();
return;
}
return { user: session.user };
}
}; this looks like a big workaround. I'd have to repeat the same getInitialProps over and over again for all the pages that require authentication. Also: what if I navigate on the client side? It would simply not fetch the user. There are dozens of workarounds that I've seen recently. There is one big question: How to accomplish (cookie-based) authentication in nextjs with both SSR and CSR? If I were able to get the authentication information on the server side already, pre-render the "logged-in" page and the client just keeps going with that... That'd be nice. But I haven't seen such before. |
Beta Was this translation helpful? Give feedback.
-
I managed to get it working by extending my public static async getInitialProps({
ctx
}: AppContext): Promise<AppInitialProps> {
const req: any = ctx.req
return {
pageProps: {
user: req?.user
}
}
} This allowed me to access pageProps in the |
Beta Was this translation helpful? Give feedback.
-
@timneutkens Is there a current way of getting the user session as SSR on first page request, then subsequent page requests would be CSR since I'd store session in a Provider in Right now I have to implement |
Beta Was this translation helpful? Give feedback.
-
As a workaround for the usecase regarding authentication with this issue, I have created a getServerSideProps function within a helper file:
import {auth0} from '../auth0';
const LOGIN_LOCATION = '/api/auth/login';
function mergeAuth(auth, merge, res) {
if (!auth) {
res.writeHead(
307,
{
Location: LOGIN_LOCATION
}
).end();
return;
}
return {
...merge,
props: {
...merge.props,
auth
}
}
}
export async function getServerSideProps(original) {
if (typeof original !== 'function') {
return mergeAuth(await auth0.getSession(original.req), undefined, original.res);
}
return async function (context) {
const originalReturn = original(context);
return mergeAuth(await auth0.getSession(context.req), originalReturn, context.res);
};
} And on a page that needs authentication I do this: export {getServerSideProps} from '../utils/ssrHelper/authentication'; This saves alot of boilerplate.
Actually this does trigger both on the client and server side. This code above will get you SSR and CSR with auth checks. It works just fine and that's nice. |
Beta Was this translation helpful? Give feedback.
-
Edit: It seems the RFC by Tim is the best way to go for the future (once it exists): #14890 @AmazingTurtle I think this is possible with the following pattern (original source): export async function getServerSideProps(context) {
// Status code 307 is a better 302
context.res.writeHead(307, { Location: '/login' }).end();
} Caveat: One downside to this approach is that on client-side navigation it throws an error (see #14547): Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client There is also a // Only for Next.js 9.4.5+
export async function getServerSideProps(context) {
context.res.redirect('/login');
} If this works for you, can you update your comment above for anyone else who finds it? |
Beta Was this translation helpful? Give feedback.
-
So can |
Beta Was this translation helpful? Give feedback.
-
In case this is useful to anyone, I found a kind of weird workaround to be able to access some request information only in SSR and avoid the automatic serialization of NextJS: function MyApp({ getReqCookie }) {
const cookie = getReqCookie && getReqCookie();
// cookie is available in SSR and undefined in Client
...
}
MyApp.getInitialProps = async (appContext) => {
const request = appContext?.ctx?.req;
return {
// workaround cause getServerSideProps is not possible in _app
getReqCookie() {
return request?.headers?.cookie;
},
};
}; |
Beta Was this translation helpful? Give feedback.
-
This is a very needed feature. |
Beta Was this translation helpful? Give feedback.
-
Just to give this even more attention, this is a much needed feature. |
Beta Was this translation helpful? Give feedback.
-
I use a simple workaround that don't need too much changes in your code
` const MyApp = ({ Component, pageProps }) => <Component {...pageProps} /> MyApp.getInitialProps = async (appContext) => {
} export default MyApp`
` export async function getServerSideProps(ctx){
} |
Beta Was this translation helpful? Give feedback.
-
Any ETA for updated API? getServerSideProps in _app |
Beta Was this translation helpful? Give feedback.
-
I also had the similar problem where I had to fetch loggedIn user details from my Auth api. I solved it by wrapping my whole app inside a context provider, then using a set function for the initialState, which will remember if it was called before and fetch user details only once. Then in my each page, wherever I require these user details, I used the context to see if details are available and call the set function if details are not available. This way I think I achieved: Only one request to fetch user details |
Beta Was this translation helpful? Give feedback.
-
Next-js has potential, but this makes the impulse wanting to switch to Vue. |
Beta Was this translation helpful? Give feedback.
-
isn't the new middleware stuff from Next 12 solving a lot of the issues above? |
Beta Was this translation helpful? Give feedback.
-
I recently created a small lib which might solve some of the problems mentioned here. https://github.com/abergenw/next-page-layout. This gives you the possibility to define layouts (nested) for your pages. Each layout has its own data requirements which are either passed in as "props" from a child layout/page OR through any of the supported data fetching mechanisms (getInitialProps, getServerSideProps or getStaticProps). In addition to this there's also the possibility to do client side data fetching with "useInitialProps" in a way which prevents a waterfall effect. So basically this lib gives you the tools to define your data requirements and (persisted) layouts on a page level without having to repeat yourself even if most of your pages use the same basics. There should be little need to mess with App using this approach. |
Beta Was this translation helpful? Give feedback.
-
Any updates on this @leerob @timneutkens ? |
Beta Was this translation helpful? Give feedback.
-
I am paying attention to this problem. I thought I would upgrade to 12 and use |
Beta Was this translation helpful? Give feedback.
-
Update 2022: We are working on this! It will be part of the new Next.js router. |
Beta Was this translation helpful? Give feedback.
-
Happy to share the Layouts RFC is finally out: https://twitter.com/vercel/status/1528839321070993409 🥳 |
Beta Was this translation helpful? Give feedback.
-
My specific use-case was fetching for user data once, then having that user object available in the rest of the pages' getInitialProps AND getServerSideProps. For anyone looking for a workaround: // pages/_app.js
App.getInitialProps = async (appContext) => {
const { req = {}, res } = appContext.ctx
const user = await fetchUser({ req, res })
req.user = user
} Then this // pages/index.js
export const getServerSideProps = async ({ req }) => {
req.user // fetched user from App.getInitialProps
} |
Beta Was this translation helpful? Give feedback.
-
For those wanting to share state received from a page's |
Beta Was this translation helpful? Give feedback.
-
I'm using next-firebase-auth for authentication and ALL of the pages on my app need to have the user context. So, I would be okay with losing the static optimization as all the pages are rendered server-side either way. Is there any timeline on when we might have the |
Beta Was this translation helpful? Give feedback.
-
Update: We’re excited to announce Next.js 13, which includes the new Inside the You can leave feedback here: #41745 |
Beta Was this translation helpful? Give feedback.
-
Hello @leerob I am trying to migrate my project from My actual purpose is to call an API of
Generally, this approach is used in most projects because authentication is the very first thing we need to setup/integrate. well, above are my points that tell this issue is still not resolved, and I request you to reopen this todo. |
Beta Was this translation helpful? Give feedback.
Update: We’re excited to announce Next.js 13, which includes the new
app/
directory (beta) with support for nested layouts, colocation of data fetching, streaming, Server Components by default, and much more.Inside the
app/
directory, there is a powerful new way to fetch data with React’suse()
hook and the extended Webfetch()
API. This allows you to colocate data fetching directly inside components for the most flexibility, including inside layouts.You can leave feedback here: #41745