Latest Tutorials

Learn about the latest technologies from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

Angular SSR: The Browser Is Not The Server

In this article, we're talking about blazing fast performance with Angular Universal with server-side-rendering (SSR). One of the great things about SSR is that we get to use the same code on our frontend and our backend to render our app. Well, sort of. When we use the same code, right off the bat we have a problem: the browser is not the server and there are differences between what we can do in each environment. The benefit of rendering our Angular app on the server is that we can fetch data privately and efficiently before we send anything to the browser. Our server is (in this case) Node.js, and so on the server we can use: But the browser is not the server. And if we try to call browser-only APIs, then we'll break SSR. Well, three things come to mind that are exclusive to the browser: While it's awesome that our Angular application can share code between the server and the browser, if we want to use any of these objects, we need to execute a different logic path based on the current runtime: Node.js or the browser window. Below, I'm going to show you one of the techniques for doing that. Let's add internationalization to your application. Let's display product prices in three currencies: US dollars, British pounds, and Polish zloty. The application should pick a currency based on browser settings, and if a given language is not supported, it should fall back to Polish zloty. Let's generate a new service: Now let's detect user language and implement the getCurrencyCode() method that returns one of the three available currency codes: Now in one of our components, say ProductDetailsComponent , we can use this service to get the user's currency: Then we could use the userCurrency in a view with the currency pipe: From now on, prices should display in a currency defined by the user's localization settings. This is great, right? Well, no. Unfortunately, this logic breaks SSR: It would help if we had a mechanism to detect whether the current runtime is the browser or the server - and thankfully that's why we have isPlatformBrowser() and isPlatformServer() : Angular ships with the isPlatformBrowser() and isPlatformServer() methods in the @angular/common package. Each of these methods accepts one parameter: the platform ID. It can be retrieved via the Dependency Injection mechanism using the injection token PLATFORM_ID available in the @angular/core package. So to change our internationalization service I18nService above, Add these new imports: Modify the service constructor to only use the window object if an instance of the service executes in the browser: This should be enough for SSR to start working again but we don't get internationalization pre-rendered on our server-side render -- internationalization won't appear until after the app loads. So what we need is a way to know what language to render from the origin HTTP request to the server . The question now is how to retrieve information about user language on the server. Is it even possible? Yes, it is. When you're performing a request from the browser, the browser adds a bunch of HTTP headers that you might not usually think about. One of these headers is Accept-Language which tells us what language the user wants! For example, the header might come through like this: Accept-Language: en-US,en;q=0.5 . Angular Universal allows you to get an object that represents an HTTP request. It's available via Dependency Injection under the REQUEST token from the @nguniversal/express-engine/tokens package. The Request object contains the following fields: So we update our imports by adding the Request object, the REQUEST injection token, and the Optional decorator: Change the constructor to inject the Request object and retrieve user language from the Accept-Language header: If we use a tool like curl or Postman, we can verify that language settings are working within the pre-render (or fall back to Polish zloty when the Accept-Language header is missing): Angular Universal is a super-powerful tool in your Angular toolbox -- but if you're just used to writing frontend Angular, you might find it a bit tricky. But with a little guidance, you'll find you can get blazing-fast Angular apps. Check out the course Mastering Angular Universal: Build Blazing-fast Server-Side-Rendered Angular App s

Thumbnail Image of Tutorial Angular SSR: The Browser Is Not The Server

How to Handle Effects Using Hooks in React with TypeScript

There are 2 hooks to handle side-effects in React: The first one fires after layout and paint, during a deferred event. The second one works synchronously before the next paint, and used to handle effects that are visible to a user. The useEffect hook accepts 2 arguments: By default, useEffect fires on every re-render. If you need it to fire only when certain values change use the second argument to point out those values. You can also return from an effect a clean-up function. The clean-up function runs before the component is removed from the UI to prevent memory leaks. You don't need any additional typings for the useEffect hook. However, TypeScript knows about its inner structure and type signatures, so there is no chance to compile something like: This hook is the same in a sense of type signatures as the useEffect hook. So you can re-write a counter component using it: It also doesn't require any additional typings.

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

How to Use useReducer with TypeScript

The useReducer hook is a hook that allows you to create a state, update it, and share its data across different components. (Its core logic is similar to Redux .) It takes a reducer-function and an initial state as arguments and returns a tuple of a new state and a dispatch function. The reducer must extend the Reducer<State, Action> type, which is a function that takes a state and an action as arguments, updates the state, and returns the updated state: A state is usually an object with some data. Let's use a counter as an example. If we want to keep track of a current counter value, we can create an object with a value field: We will use this State type as a type parameter for the Reducer type later, and the initialState object will be the default value for the state. An action is sort of like an event, which triggers the state updates. For example, a counter can have 2 actions: for increasing and decreasing its value. Usually, an action is an object that has a type and payload . The type is like an ID of this action, and a payload is a data that the action transfers. Now that we have a state and a set of actions we can create a reducer. When a reducer is ready, we can use the useReducer hook. Now we combine our initial state, reducer, and actions with a component:

How to Use React Refs with TypeScript

Refs provide a way to access DOM nodes or React elements created in the render method. Also, they can be used to store some references to entities or objects for accessing them later. To use refs with functional components use a special useRef hook . It is a generic function, so we can pass a type-parameter, that will tell TypeScript what type is acceptable for this ref. Initially, we set a ref's value as null , because it will be set later on render. That's why we need to null-check inputRef.current later in onFocus . Also, inputRef itself is an object that contains a value in the current field. So to access the real element we need to get a value of this field. In class components, you can store refs in private class fields after creating them with createRef . When you need to access some data but you don't need to share it across components and don't need to change it you can use refs too.

How to Use React Context with TypeScript

React Context provides a way to pass data through the component tree without having to pass props down manually at every level. Use it when you need to share data “globally”, between many components on different levels to a component tree. To create a context use React.createContext : With TypeScript, you can declare a type for a context , so that TypeScript will know what types are acceptable for this context. However, there is a catch. If we have a data structure that can't have default values we can't just type a context: There are 2 workarounds here. The first one allows not to assign values to fields of a User type. So when we pass a defaultUser as an initial value there no errors: But in this case, we lose in type-safety a bit because we can miss some values later. The second option is to set null as an initial value: This way we don't lose in type-safety, but we will need to check if the context value is null every time we access it. When created, a context can be used in components. To give access to a context value we need to use Provider : The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider . To get a value we need to use the Consumer component: It uses a render-prop pattern . This means that it accepts a function instead of a component as a child. It will then pass a context value as an argument to this function. You can also use useContext hook to get access to a context value. This makes the component's source much simpler and cleaner.